• 《C#多线程编程实战》2.6 ManualResetEventSlim


    这个比较好理解的。

    正如书上所言,如同一直在打开的大门的屋子,谁要进去,谁就自己的关门,出来的时候在开开。

    常用的方法 有三个:

    Set()  //设置为有信号,也就是让等待的线程不用继续等待,唤醒等待的线程。

    Reset() //设置为 无信号 也就是让没有等待的线程变成需要等待的状态,需要配合Wait的方法。

    Wait()//等待,堵塞线程,除非接受信号【set方法】才会释放

    那么书上的例子:

     class Program
        {
            static void Test(string threadName,int seconds)
            {
                Console.WriteLine($"{threadName} falls to sleep");
                Thread.Sleep(TimeSpan.FromSeconds(seconds));
                Console.WriteLine($"{threadName} waits for the gates to open");
                _mainEvent.Wait();
               
                Console.WriteLine($"{threadName} enters the gats");
            }
            static ManualResetEventSlim _mainEvent = new ManualResetEventSlim(false);
            static void Main(string[] args)
            {
                var t1 = new Thread(() => Test("Thread 1", 5));
                var t2 = new Thread(() => Test("Thread 2", 6));
                var t3 = new Thread(() => Test("Thread 3", 12));
                t1.Start();
                t2.Start();
                t3.Start();
                Thread.Sleep(TimeSpan.FromSeconds(6));
                Console.WriteLine("the gates are now open");
                _mainEvent.Set();
                Thread.Sleep(TimeSpan.FromSeconds(2));
                _mainEvent.Reset();
                
                Console.WriteLine("the gates have been closed!");
                Thread.Sleep(TimeSpan.FromSeconds(10));
                Console.WriteLine("the fatres are now ioen for the second time !");
                _mainEvent.Set();
                Thread.Sleep(TimeSpan.FromSeconds(2));
                Console.WriteLine("the gates have been closed");
                _mainEvent.Reset();
                Console.ReadKey();
    
            }
        }

    运行 起来 ,再配合书上的解读。

    稍微思考一下 还是很好理解的。

    就是干什么事情,会比较麻烦,但是对线程的每一步都会全面的掌握。

    初始化为false时

    一般运行顺序就是

    Reset()//设置需要等待

    Wait()//实际等待

    Set()//释放线程

    一般来说 在初始化ManualResetEventSlim都是false。

    如果是true,必须手动设置Reset一次。

  • 相关阅读:
    python idea 利用树莓派做家庭报警系统
    Browserslist: caniuse-lite is outdated. Please run next command `npm update`
    maven项目最外层有个红x,项目其他没有x
    要取消:根据 sitemap 的规则[0],当前页面 [pages/index/index] 将被索引
    MySQL的DATE_FORMAT()用法
    maven项目的java和resources等文件夹不在Java Resources的文件夹里,并且缺少Deployment...
    小程序开发demo及资源
    wx.requestSubscribeMessage 订阅消息
    java获取年月日
    goland 文件头自动注释
  • 原文地址:https://www.cnblogs.com/T-ARF/p/9395194.html
Copyright © 2020-2023  润新知