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

导读:本篇文章讲解 《C#多线程编程实战》2.6 ManualResetEventSlim,希望对大家有帮助,欢迎收藏,转发!站点地址:www.bmabk.com

这个比较好理解的。

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

常用的方法 有三个:

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

 

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。

文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/12704.html

(0)
小半的头像小半

相关推荐

极客之音——专业性很强的中文编程技术网站,欢迎收藏到浏览器,订阅我们!