• 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     }

    执行结果

  • 相关阅读:
    css兼容性大坑
    JS获取元素CSS值
    calendar的一些操作
    java日期工具类
    redis的一些操作
    webstorm ES6 转 ES5
    基于时间的动画算法
    3434
    MySQL登陆知识
    MySQL密码知识点
  • 原文地址:https://www.cnblogs.com/yangda/p/12587580.html
Copyright © 2020-2023  润新知