【发布时间】:2009-04-10 00:09:45
【问题描述】:
假设 ThreadA 和 ThreadB 在同一个 AutoResetEvent 上都按此顺序调用 WaitOne()。设置事件后,为什么释放的是 ThreadB 而不是 ThreadA?
我进行了一项测试,以了解当您设置多个线程正在等待的 AutoResetEvent 时会发生什么:
private static void Test()
{
// two threads - waiting for the same autoreset event
// start it unset i.e. closed i.e. anything calling WaitOne() will block
AutoResetEvent autoEvent = new AutoResetEvent(false);
Thread thread1 = new Thread(new ThreadStart(WriteSomeMessageToTheConsole));
thread1.Start(); // this will now block until we set the event
Thread thread2 = new Thread(new ThreadStart(WriteSomeOtherMessageToTheConsole));
thread2.Start(); // this will now also block until we set the event
// simulate some other stuff
Console.WriteLine("Doing stuff...");
Thread.Sleep(5000);
Console.WriteLine("Stuff done.");
// set the event - I thought this would mean both waiting threads are allowed to continue
// BUT thread2 runs and thread1 stays blocked indefinitely
// So I guess I was wrong and that Set only releases one thread in WaitOne()?
// And why thread2 first?
autoEvent1.Set();
}
代码当然没用;这只是一个米老鼠的例子。这并不重要/紧急。不过我还是有兴趣了解更多...
【问题讨论】:
-
尝试调用autoEvent1.Set();再次查看其他线程是否会被释放。我想你需要把开关转两下。
-
嗨 - 是的,我马上就尝试过了 - 我可以让第二个线程继续第二次调用 Set() - 但前提是我引入了延迟,例如调用 Thread.Sleep()。
-
我目前更感兴趣的是看看是否有人真的知道被释放的线程是随机的。文档说线程排队表明某种排序(这就是为什么我希望第一个线程首先释放)。
-
来自这里:msdn.microsoft.com/en-us/library/… 不能保证每次调用 Set 方法都会释放一个线程。如果两个调用靠得太近,以至于第二个调用发生在一个线程被释放之前,那么只有一个线程被释放。
-
文档在哪里 :-)
标签: c# .net multithreading resetevent