Which methods can be used to make thread wait for an event and then continue its execution? Which methods can be used to make thread wait for an event and then continue its execution? multithreading multithreading

Which methods can be used to make thread wait for an event and then continue its execution?


I often use the AutoResetEvent wait handle when I need 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}


You can use a ManualResetEvent for this.

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

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

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