working example of WaitHandle.WaitAny() please

  • Thread starter Thread starter pokémon
  • Start date Start date
pokémon,

Here is an example:

private mobjWaitHandle1 = new ManualResetEvent();
private mobjWaitHandle2 = new ManualResetEvent();

public void TestWaitAny()
{
// Start threads in the threadpool.
ThreadPool.QueueUserWorkItem(new WaitCallback(WaitCallbackHandler),
mobjWaitHandle1);
ThreadPool.QueueUserWorkItem(new WaitCallback(WaitCallbackHandler),
mobjWaitHandle2);

// Wait on the wait handles.
WaitHandle.WaitAny(new WaitHandle[]{mobjWaitHandle1, mobjWaitHandle2});
}

private void WaitCallbackHandler(object state)
{
// Create a randomizer and get a random number of seconds between 1 and
10 to wait.
Random pobjRandom = new Random();

// Wait on this thread for a number of seconds equal to the number
passed in through the state.
Thread.Sleep(pobjRandom.Next(1, 10) * 1000);

// Signal the wait handle passed in.
((ManualResetEvent) state).Set();

// Get out.
return;
}

Basically, two threads are started and they both wait for a random
number of seconds between 1 and 10. Once they are done, they signal the
event that is passed in. The main thread calling the threading code waits
until one of the threads signals through the event.

Hope this helps.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Back
Top