我想澄清下面的代码是如何工作的。我列出了我的疑惑,以获得您的答复。AutoResetEvent澄清
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);
选择从线程池线程,使该线程执行CodingInCSharp。 WaitCallback的用途是在Main()线程 完成其执行后执行该方法。
autoEvent.WaitOne(1000,false)
等待1秒,从 “CodingInCSharp”) 柜面得到信号,如果我使用了WaitOne(1000 真),将它杀死它 线程池收到的线程?
如果我没有设置
((AutoResetEvent)stateInfo).Set();
那么Main()会无限期地等待信号吗?