Using system;
Using system. Threading;
Public sealed class app
{
// Define an array with two autoresetevent waithandles.
Static waithandle [] waithandles = new waithandle []
{
New autoresetevent (false ),
New autoresetevent (false)
};
// Define a random number generator for testing.
Static random r = new random ();
Static void main ()
{
// Queue up two tasks on two different threads;
// Wait until all tasks are completed.
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 );
// The time shown below shocould match the longest task.
Console. writeline ("both tasks are completed (Time waited = {0 })",
(Datetime. Now-Dt). totalmilliseconds );
// Queue up two tasks on two different threads;
// Wait until any tasks are completed.
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 );
// The time shown below shocould 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 ("grouping a task for {0} milliseconds.", time );
Thread. Sleep (time );
Are. Set ();
}
}
// This code produces output similar to the following:
//
// Main thread is waiting for both tasks to complete.
// Specify a task for 7000 milliseconds.
// Specify a task for 4000 milliseconds.
// Both tasks are completed (Time waited = 7064.8052)
//
// The main thread is waiting for either task to complete.
// Specify a task for 2000 milliseconds.
// Specify a task for 2000 milliseconds.
// Task 1 finished first (Time waited = 2000.6528 ).