[ACCEPTED]-Which methods can be used to make thread wait for an event and then continue its execution?-event-handling
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
}
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.
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
We use cookies to improve the performance of the site. By staying on our site, you agree to the terms of use of cookies.