I have a thread running that delegates out some tasks. When a single task is complete, an event is raised saying that it has completed. These tasks need to be run in a specific order and need to wait for the previous task to finish. How can I make the thread wait until it receives the "task completed" event? (Aside from the obvious eventhandler that sets a flag and then a while loop polling the flag)
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
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With