Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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)

like image 474
MGSoto Avatar asked Aug 07 '09 17:08

MGSoto


1 Answers

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
}
like image 124
Fredrik Mörk Avatar answered Oct 09 '22 20:10

Fredrik Mörk