我想澄清下面的代码是如何工作的。我已经逐项列出了我的怀疑,以获得您的答复。
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);在初始阶段,信号被设置为false.
ThreadPool.QueueUserWorkItem(new WaitCallback(CodingInCSharp), autoEvent);从ThreadPool中选择一个线程并使该线程执行CodingInCSharp。Main() WaitCallback的目的是在Main()线程完成其WaitCallback之后执行该方法
等待1秒,从“CodingInCSharp”获得信号),如果我使用WaitOne(1000,true),它会杀死它从CodingInCSharp收到的线程吗?
发布于 2009-11-24 05:01:24
一旦线程池线程可用,WaitCallback就在并发中执行到Main方法。
主方法等待线程池线程上的CodingInCSharp方法设置信号1秒。如果在1秒内设置了信号,主方法将打印"Coding singalled(coding finished)"。如果在1秒内没有设置信号,则主方法将中止等待信号并打印"Timed out waiting for coding"。在这两种情况下,主方法都继续等待按下密钥。
设置信号或到达超时并不会“杀死”线程。
如果没有设置信号,主方法将不会无限期地等待,因为如果信号在1秒内没有设置,等待信号将被中止。
https://stackoverflow.com/questions/1787816
复制相似问题