可以使用哪些方法使线程等待事件然后继续执行?

我有一个线程运行,委托一些任务。 单个任务完成后,会发出一个事件,说明它已完成。 这些任务需要按特定顺序运行,需要等待上一个任务完成。 如何让线程等到收到“任务完成”事件? (除了设置标志然后循环轮询标志的明显的事件处理程序)

当我需要等待异步任务完成时,我经常使用AutoResetEvent等待句柄:

 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 } 

一种选择是使用EventWaitHandle来表示完成。

您可以使用ManualResetEvent 。

需要先处理的线程只接受resetEvent,并等到设置事件结束。

需要等待的线程可以保存它的句柄,并调用resetEvent.WaitOne()。 这将阻止该线程,直到第一次完成。

这允许您以非常干净的方式处理事件的阻塞和排序。

通过使用工作线程完成后调用的回调方法,我得到了很好的结果。 它击败了轮询并且可以很容易地将参数传递回调用者。