ManualResetEvent被用于在** 两个或多个线程间** 进行线程信号发送。 多个线程可以通过调用ManualResetEvent对象的WaitOne方法进入等待或阻塞状态。当控制线程调用Set()方法,所有等待线程将恢复并继续执行。 以下是使用ManualResetEvent的例子,确保多线程调用时 First->Second->Third 的顺序不变。[若看完仍有疑惑,请点击传送门:
using System.Threading;public class Foo {private readonly ManualResetEvent firstDone = new ManualResetEvent(false);
private readonly ManualResetEvent secondDone = new ManualResetEvent(false); public Foo() {}public void First(Action printFirst) {// printFirst() outputs "first". Do not change or remove this line.printFirst();firstDone.Set();
}public void Second(Action printSecond) {firstDone.WaitOne();// printSecond() outputs "second". Do not change or remove this line.printSecond();secondDone.Set();
}public void Third(Action printThird) {secondDone.WaitOne();// printThird() outputs "third". Do not change or remove this line.printThird();
}
}