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

23,154

Solution 1

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
}

Solution 2

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

Solution 3

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.

Share:
23,154
MGSoto
Author by

MGSoto

Nothing really to say.

Updated on July 29, 2022

Comments

  • MGSoto
    MGSoto almost 2 years

    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)

  • MGSoto
    MGSoto almost 15 years
    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?
  • Fredrik Mörk
    Fredrik Mörk almost 15 years
    @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.
  • Michal Dobrodenka
    Michal Dobrodenka almost 11 years
    Don't forget, that AutoResetEvent, WaitHandles etc implements IDisposable