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

  • 相关阅读:
    How to produce the first draft of research paper?
    ETL
    BDA chapter 10
    <转>Java转iOS-第一个项目总结(2):遇到问题和解决方案
    <转>从Java转iOS第一个项目总结
    (转)总结iOS 8和Xcode 6的各种坑
    iOS开发之Xcode6之后不再自动创建Pch预编译文件,该如何解决这个问题?
    iOS开发:Objective-C中通知与协议的区别?
    PT和PX是什么鬼?
    使用cocoaPods经常出现的问题以及解决方案
  • 原文地址:https://www.cnblogs.com/T-ARF/p/9395194.html
Copyright © 2011-2022 走看看