线程之间灵活传递信号(ManualResetEventSlim )

当主程序启动时,首先创建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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值