MGSoto
MGSoto

Reputation: 2363

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)

Upvotes: 16

Views: 27198

Answers (4)

Ed Power
Ed Power

Reputation: 8531

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

Upvotes: 0

Reed Copsey
Reed Copsey

Reputation: 564413

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.

Upvotes: 2

Fredrik Mörk
Fredrik Mörk

Reputation: 158309

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
}

Upvotes: 28

bdonlan
bdonlan

Reputation: 231143

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

Upvotes: 5

Related Questions