The following code example shows how two threads can do background tasks while the Main thread waits for the tasks to complete using the static WaitAny and WaitAll methods of the WaitHandle class.
| |
using System; using System.Threading;public sealed class App { static WaitHandle[] waitHandles = new WaitHandle[] { new AutoResetEvent(false), new AutoResetEvent(false) }; static Random r = new Random(); static void Main() { DateTime dt = DateTime.Now; Console.WriteLine("Main thread is waiting for BOTH tasks to complete."); ThreadPool.QueueUserWorkItem(new WaitCallback(DoTask), waitHandles[0]); ThreadPool.QueueUserWorkItem(new WaitCallback(DoTask), waitHandles[1]); WaitHandle.WaitAll(waitHandles); Console.WriteLine("Both tasks are completed (time waited={0})", (DateTime.Now - dt).TotalMilliseconds); dt = DateTime.Now; Console.WriteLine(); 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); 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(); } }
|