【发布时间】:2009-11-24 13:03:29
【问题描述】:
我想澄清以下代码的工作原理。我已逐项列出我的疑问以获得您的回复。
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);从 ThreadPool 中选择一个线程并让该线程执行 CodingInCSharp。 WaitCallback 的目的是执行 Main() 线程之后的方法 完成它的执行。
-
autoEvent.WaitOne(1000,false)等待 1 秒从“CodingInCSharp”获取信号) 如果我使用 WaitOne(1000,true),它会杀死它收到的线程吗 线程池?
如果我没有设置
((AutoResetEvent)stateInfo).Set();,Main() 会无限期地等待信号吗?
【问题讨论】:
标签: c# multithreading