我想澄清以下代码的工作方式。我逐一列出了我的疑问,以得到您的答复。
class AutoResetEventDemo
{
static AutoResetEvent autoEvent = new AutoResetEvent(false);
static void Main()
{
Console.WriteLine("...Main starting...");
ThreadPool.QueueUserWorkItem
(new WaitCallback(CodingInCSharp), autoEvent);
if(autoEvent.WaitOne(1000, false))
{
Console.WriteLine("Coding singalled(coding finished)");
}
else
{
Console.WriteLine("Timed out waiting for coding");
}
Console.WriteLine("..Main ending...");
Console.ReadKey(true);
}
static void CodingInCSharp(object stateInfo)
{
Console.WriteLine("Coding Begins.");
Thread.Sleep(new Random().Next(100, 2000));
Console.WriteLine("Coding Over");
((AutoResetEvent)stateInfo).Set();
}
}
static AutoResetEvent autoEvent = new AutoResetEvent(false);
在初始阶段,信号设置为假。
ThreadPool.QueueUserWorkItem(new WaitCallback(CodingInCSharp), autoEvent);
从ThreadPool中选择一个线程,并使该线程执行CodingInCSharp。
WaitCallback的目的是在Main()线程之后执行该方法
完成执行。
autoEvent.WaitOne(1000,false)
等待1秒钟,以从“CodingInCSharp”获得信号)
如果我使用WaitOne(1000, true ),它将杀死从它接收到的线程
线程池?
((AutoResetEvent)stateInfo).Set();
,Main()将无限期地等待信号吗? 最佳答案
线程池线程可用后,将在中同时在中执行WaitCallback到Main方法。
Main方法在线程池线程上等待1秒钟以等待CodingInCSharp方法设置信号。如果在1秒钟内设置了信号,则Main方法将输出"Coding singalled(coding finished)"
。如果未在1秒钟内设置信号,则Main方法将中止等待信号并打印"Timed out waiting for coding"
。在这两种情况下,Main方法都会继续等待按键被按下。
设置信号或达到超时不会“杀死”线程。
如果未设置信号,Main方法将不会无限期等待,因为如果未在1秒钟内设置信号,则等待信号将中止。
关于c# - AutoResetEvent澄清,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1787816/