zoukankan      html  css  js  c++  java
  • 《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一次。

  • 相关阅读:
    ElementUI 之 Message,自动弹出,信息不显示问题
    eslint 对下一行不要校验报错
    <input type="file"> accept属性筛选文件类型
    纯 css 控制隔行变色
    本地启动服务,两个进程分别监听两个端口,导致两个 URL 不同
    tap 事件会触发两次问题
    时间宝贵-----
    有些人,得到和失去,你都会后悔!
    前调清新,中调醇厚,后调悠长。
    office 格式定义
  • 原文地址:https://www.cnblogs.com/T-ARF/p/9395194.html
Copyright © 2011-2022 走看看