views:

344

answers:

4

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)

+3  A: 

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

bdonlan
could you elaborate? explain this better and I will most definately vote up!
Firoso
+1. @firoso, there is much detail in the msdn article.
SnOrfus
Including examples in multiple languages
bdonlan
which doesn't include a description involving application to a specific instance, I think it's a good response, just not "the" good response.
Firoso
+8  A: 

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
}
Fredrik Mörk
Based off the first answer, I am doing something very similar to this. What is the difference between AutoResetEvent and EventWaitHandle initialized with EventResetMode.AutoReset?
MGSoto
@MGSoto: I think the difference is minimal (if any): `AutoResetEvent` inherits from `EventWaitHandle`, and seems to use the constructor of its base class to pass `EventResetMode.AutoReset` to it.
Fredrik Mörk
+1  A: 

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.

Reed Copsey
A: 

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.

ebpower