当主程序启动时,首先创建ManualResetEventSlim 类的一个实例。然后启动三个线程,等待事件信号通知它们继续执行。
1 /// <summary> 2 /// 创建 ManualResetEventSlim 实例 3 /// </summary> 4 private static ManualResetEventSlim _mainEvent = new ManualResetEventSlim(false); 5 6 /// <summary> 7 /// 接收信号继续执行 8 /// </summary> 9 /// <param name="threadName">线程名</param> 10 /// <param name="secods">时间(秒)</param> 11 public void TravelThroughGates(string threadName, int secods) 12 { 13 // threadName falls to sleep 14 System.Threading.Thread.Sleep(TimeSpan.FromSeconds(secods)); 15 16 // threadName waits for the gates to open 17 _mainEvent.Wait(); // 阻止当前线程,直到接收到信号 18 19 // threadName enters the gates 20 Console.WriteLine($"{threadName} 继续执行"); 21 22 }
线程只有在ManualResetEventSlim 对象发出信号才能继续执行,不然只有继续等待,直到接接收到信号。
1 /// <summary> 2 /// 输出 3 /// </summary> 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 open 16 _mainEvent.Set(); // 发射信号 17 18 System.Threading.Thread.Sleep(TimeSpan.FromSeconds(2)); 19 _mainEvent.Reset(); // 关闭信号 20 21 // The gates have been closed 22 System.Threading.Thread.Sleep(TimeSpan.FromSeconds(10)); 23 24 // The gates are now open for the second time 25 _mainEvent.Set(); // 发射信号 26 27 System.Threading.Thread.Sleep(TimeSpan.FromSeconds(2)); 28 29 //The gates have been closed 30 _mainEvent.Reset(); // 关闭信号 31 }
原文地址:https://www.cnblogs.com/KevinTong/p/11462595.html
时间: 2024-10-14 15:57:06