?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();
}
}