我想澄清下面的代碼是如何工作的。我列出了我的疑惑,以獲得您的答覆。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()會無限期地等待信號嗎?