开发者

Strange behaviour for threads in ASP.NET

public void WriteToLog(string Msg)
{
    //Write to Log
}

public static void Apple()
{
    WriteToLog("Apple Started"); // third log line
}

public void CallFunction()
{
    Thread EmailThread = new Thread(new ThreadStart(Apple));
    WriteToLog(EmailThread.ThreadState.ToString()); // first log line
    EmailThread.Start();
    WriteToLog(EmailThread.ThreadState.ToString()); // second log line
}

in the log file, I get first line and second line. but i can't get the third line.

I can get the third line if i simply call the Apple function.

and the first line is Unstarted and second line is running.

there is no third line.

when i write while loop under the second log line,

while(EmailThread.ThreadState.ToString()=="Running")
{
    WriteToLog("Thread running");
}

It becomes infinite loop. I had to stop the IIS.

Is it a strange behavior?

All the functions inside Apple doesn开发者_运维百科't seem working either.

but the thread state is running..

I m lost. Any idea?

or is it because of the new thread, it can't write to log file? the same log file? but i already tried 2 different log files. It is still not working...

and I wrote the function to write to log file at the start of the Apple.


Is the logging mechanism multi-threaded?

I would suggest you add a critical section to your code to ensure that the logging is only occuring from one thread at a time, otherwise they could be flushing the buffer or overwriting the output or something funny like that.

To do this implement something like this:

static readonly object threadLock = new object();

public void WriteToLog(string Msg)   
{
    lock(threadLock)
    {   
        //Write to Log
    }
}

Hope that helps.

UPDATED

Also I would try not making the thread a local variable. It is possible it is getting finalised before it's code is executing. Define it as a field on the class like so:

public class SomeClass
{
   private Thread EmailThread;

   public void WriteToLog(string Msg) 
   { 
       //Write to Log 
   } 

   public static void Apple() 
   { 
       WriteToLog("Apple Started"); // third log line 
   } 

   public void CallFunction() 
   { 
       EmailThread = new Thread(new ThreadStart(Apple)); 
       WriteToLog(EmailThread.ThreadState.ToString()); // first log line 
       EmailThread.Start(); 
       WriteToLog(EmailThread.ThreadState.ToString()); // second log line 
  } 
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜