MSDN上的示例代碼
https://msdn.microsoft.com/zh-cn/library/system.threading.waithandle(v=vs.110).aspx
……//前面的代碼省略了
Console.WriteLine("The main thread is waiting for either task to complete.");
ThreadPool.QueueUserWorkItem(new WaitCallback(DoTask), waitHandles[0]);
ThreadPool.QueueUserWorkItem(new WaitCallback(DoTask), waitHandles[1]);
int index = WaitHandle.WaitAny(waitHandles);
// The time shown below should match the shortest task.
Console.WriteLine("Task {0} finished first (time waited={1}).",
index + 1, (DateTime.Now - dt).TotalMilliseconds);
}
static void DoTask(Object state)
{
AutoResetEvent are = (AutoResetEvent) state;
int time = 1000 * r.Next(2, 10);
Console.WriteLine("Performing a task for {0} milliseconds.", time);
Thread.Sleep(time);
are.Set();
}
輸出的結果:
// The main thread is waiting for either task to complete.
// Performing a task for 2000 milliseconds.
// Performing a task for 2000 milliseconds.
// Task 1 finished first (time waited=2000.6528).
問題:既然是WaitAny,怎麼兩個任務都執行了呢?應該是執行最快的任務結束後,主線程就很快結束了,不會等第二個任務的。不知道為什麼?
理論上是這樣,但是不確定。盡管waitany只在某個信號量被重置後執行,但是可能主線程並沒有被調度,而此時另一個線程也執行完了。
特別是單處理器的情況下。這個是有一定概率的。你可以開100個線程看看,就能看到結果。