[ACCEPTED]-Which methods can be used to make thread wait for an event and then continue its execution?-event-handling

Accepted answer
Score: 28

I often use the AutoResetEvent wait handle when I need 1 to wait for an asynchronous task to finish:

public void PerformAsyncTasks()
{
    SomeClass someObj = new SomeClass()
    AutoResetEvent waitHandle = new AutoResetEvent(false); 
    // create and attach event handler for the "Completed" event
    EventHandler eventHandler = delegate(object sender, EventArgs e) 
    {
        waitHandle.Set();  // signal that the finished event was raised
    } 
    someObj.TaskCompleted += eventHandler;

    // call the async method
    someObj.PerformFirstTaskAsync();    
    // Wait until the event handler is invoked
    waitHandle.WaitOne();
    // the completed event has been raised, go on with the next one
    someObj.PerformSecondTaskAsync();
    waitHandle.WaitOne();
    // ...and so on
}
Score: 5

One option would be to use an EventWaitHandle to signal 1 completion.

Score: 2

You can use a ManualResetEvent for this.

The thread that 7 needs to process first just takes the resetEvent, and 6 waits until the end to Set the event.

The 5 thread that needs to wait can hold a handle 4 to it, and call resetEvent.WaitOne(). This 3 will block that thread until the first completes.

This 2 allows you to handle blocking and ordering 1 of events in a very clean manner.

Score: 0

I've had good results by using a callback 3 method that the worker thread calls when 2 its done. It beats polling and makes it 1 easy to pass parameters back to the caller.

More Related questions