C#线程同步AutoResetEvent类介绍

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     }

执行结果

 

posted @ 2020-03-28 16:00  虔城墨客  阅读(270)  评论(0编辑  收藏  举报