假设 ThreadA 和 ThreadB 都WaitOne()
在同一个 AutoResetEvent 上按此顺序调用。设置事件后,为什么释放 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();
}
代码当然没用;这只是一个米老鼠的例子。这并不重要/紧急。但无论如何我有兴趣了解更多...