当主程序启动时,首先创建ManualResetEventSlim 类的一个实例。然后启动三个线程,等待事件信号通知它们继续执行。
1 ///2 /// 创建 ManualResetEventSlim 实例 3 /// 4 private static ManualResetEventSlim _mainEvent = new ManualResetEventSlim(false); 5 6 ///7 /// 接收信号继续执行 8 /// 9 /// 线程名10 /// 时间(秒)11 public void TravelThroughGates(string threadName, int secods)12 {13 // threadName falls to sleep14 System.Threading.Thread.Sleep(TimeSpan.FromSeconds(secods));15 16 // threadName waits for the gates to open17 _mainEvent.Wait(); // 阻止当前线程,直到接收到信号18 19 // threadName enters the gates20 Console.WriteLine($"{threadName} 继续执行");21 22 }
线程只有在ManualResetEventSlim 对象发出信号才能继续执行,不然只有继续等待,直到接接收到信号。
1 ///2 /// 输出 3 /// 4 public void Print() 5 { 6 var t1 = new System.Threading.Thread(() => TravelThroughGates("Thread 1", 5)); 7 var t2 = new System.Threading.Thread(() => TravelThroughGates("Thread 2", 6)); 8 var t3 = new System.Threading.Thread(() => TravelThroughGates("Thread 3", 12)); 9 10 t1.Start();11 t2.Start();12 t3.Start();13 System.Threading.Thread.Sleep(TimeSpan.FromSeconds(6));14 15 // The gates are now open16 _mainEvent.Set(); // 发射信号17 18 System.Threading.Thread.Sleep(TimeSpan.FromSeconds(2));19 _mainEvent.Reset(); // 关闭信号20 21 // The gates have been closed22 System.Threading.Thread.Sleep(TimeSpan.FromSeconds(10));23 24 // The gates are now open for the second time25 _mainEvent.Set(); // 发射信号26 27 System.Threading.Thread.Sleep(TimeSpan.FromSeconds(2));28 29 //The gates have been closed30 _mainEvent.Reset(); // 关闭信号31 }