[英]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. 如果我简单地调用
Apple
函数,就可以得到第三行。
and the first line is Unstarted
and second line is running
. 并且,第一行是
Unstarted
和第二线running
。
there is no third line. 没有第三行。
when i write while
loop under the second log line
, 当我在
second log line
下编写while
循环时,
while(EmailThread.ThreadState.ToString()=="Running")
{
WriteToLog("Thread running");
}
It becomes infinite loop. 它变成无限循环。 I had to stop the IIS.
我不得不停止IIS。
Is it a strange behavior? 这是奇怪的行为吗?
All the functions inside Apple
doesn't seem working either. Apple
内部的所有功能似乎也不起作用。
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.
但我已经尝试了2个不同的日志文件。 It is still not working...
它仍然无法正常工作...
and I wrote the function to write to log file at the start of the Apple
. 并且我在
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
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.