2009-11-24 58 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秒内设置,则等待信号中止。