2009-11-24 55 views
1

我想澄清下面的代碼是如何工作的。我列出了我的疑惑,以獲得您的答覆。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(); 
    } 
} 
  1. static AutoResetEvent autoEvent = new AutoResetEvent(false);

    在初始階段信號被設置爲假。

  2. ThreadPool.QueueUserWorkItem(new WaitCallback(CodingInCSharp), autoEvent);

    選擇從線程池線程,使該線程執行CodingInCSharp。 WaitCallback的用途是在Main()線程 完成其執行後執行該方法。

  3. autoEvent.WaitOne(1000,false)

    等待1秒,從 「CodingInCSharp」) 櫃面得到信號,如果我使用了WaitOne(1000 ),將它殺死它 線程池收到的線程?

  4. 如果我沒有設置((AutoResetEvent)stateInfo).Set();那麼Main()會無限期地等待信號嗎?

回答

1

的WaitCallback在同時一旦一個線程池線程變得可用執行的主要方法。

Main方法在線程池線程上等待CodingInCSharp方法1秒來設置信號。如果信號設置在1秒內,Main方法將打印"Coding singalled(coding finished)"。如果信號未在1秒內設置,Main方法會中止等待信號並打印"Timed out waiting for coding"。在這兩種情況下,Main方法都會繼續等待按鍵。

設置信號或達到超時不會「殺死」一個線程。

如果未設置信號,Main方法將不會無限期等待,因爲如果信號未在1秒內設置,則等待信號中止。