首页 > 编程语言 > 详细

C#线程同步AutoResetEvent类介绍

时间:2020-03-28 16:10:13      阅读:120      评论:0      收藏:0      [点我收藏+]

AutoResetEvent 可以从一个线程向另一个线程发送通知,可以通知等待的线程有某事件发生。

通俗的来讲只有等Set()成功运行后WaitOne()才能够运行

Set是发信号,WaitOne是等待信号

 

 1   public class AutoResetEventTest
 2     {
 3 
 4         private  AutoResetEvent autoReset = null;
 5 
 6         public AutoResetEventTest(AutoResetEvent resetEvent)
 7         {
 8             autoReset = resetEvent;
 9         }
10 
11         public void Task()
12         {
13             while (true)
14             {
15                 autoReset.WaitOne();
16                 Console.WriteLine($"开始执行任务");
17             }
18         }
19 
20 
21     }
 1   public class Program
 2     {
 3         const int times = 10;
 4         static AutoResetEvent myEvent = new AutoResetEvent(false);
 5         static void Main(string[] args)
 6         {
 7             Thread thread = new Thread(() => new AutoResetEventTest(myEvent).Task());
 8             thread.Start();
 9             for (int i = 1; i < times; i++)
10             {
11                 Console.WriteLine($"第{i}次传递信号");
12                 myEvent.Set();
13                 Thread.Sleep(TimeSpan.FromSeconds(3));
14             }
15             Console.ReadLine();
16         }
17 
18     }

执行结果

技术分享图片

 

C#线程同步AutoResetEvent类介绍

原文:https://www.cnblogs.com/yangda/p/12587580.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!