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一次。

  • 相关阅读:
    sqlhelper使用指南
    大三学长带我学习JAVA。作业1. 第1讲.Java.SE入门、JDK的下载与安装、第一个Java程序、Java程序的编译与执行 大三学长带我学习JAVA。作业1.
    pku1201 Intervals
    hdu 1364 king
    pku 3268 Silver Cow Party
    pku 3169 Layout
    hdu 2680 Choose the best route
    hdu 2983
    pku 1716 Integer Intervals
    pku 2387 Til the Cows Come Home
  • 原文地址:https://www.cnblogs.com/T-ARF/p/9395194.html
Copyright © 2011-2022 走看看