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)
views:
344answers:
4
+3
A:
One option would be to use an EventWaitHandle to signal completion.
bdonlan
2009-08-07 17:57:54
could you elaborate? explain this better and I will most definately vote up!
Firoso
2009-08-07 17:58:53
+1. @firoso, there is much detail in the msdn article.
SnOrfus
2009-08-07 18:18:03
Including examples in multiple languages
bdonlan
2009-08-07 18:19:03
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
2009-08-07 18:26:45
+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
2009-08-07 18:09:45
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
2009-08-07 18:38:04
@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
2009-08-07 18:51:28
+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
2009-08-07 18:10:24
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
2009-08-07 19:03:46