C#多线程之ManualResetEvent和AutoResetEvent

来源:互联网 发布:淘宝内衣店铺怎么起名 编辑:程序博客网 时间:2024/05/18 18:16

初次体验

ManualResetEvent和AutoResetEvent主要负责多线程编程中的线程同步;以下一段是引述网上和MSDN的解析:

在.Net多线程编程中,AutoResetEvent和ManualResetEvent这两个类经常用到, 他们的用法很类似,但也有区别。Set方法将信号置为发送状态,Reset方法将信号置为不发送状态,WaitOne等待信号的发送。可以通过构造函数的参数值来决定其初始状态,若为true则非阻塞状态,为false为阻塞状态。如果某个线程调用WaitOne方法,则当信号处于发送状态时,该线程会得到信号, 继续向下执行。其区别就在调用后,AutoResetEvent.WaitOne()每次只允许一个线程进入,当某个线程得到信号后,AutoResetEvent会自动又将信号置为不发送状态,则其他调用WaitOne的线程只有继续等待.也就是说,AutoResetEvent一次只唤醒一个线程;而ManualResetEvent则可以唤醒多个线程,因为当某个线程调用了ManualResetEvent.Set()方法后,其他调用WaitOne的线程获得信号得以继续执行,而ManualResetEvent不会自动将信号置为不发送。也就是说,除非手工调用了ManualResetEvent.Reset()方法,则ManualResetEvent将一直保持有信号状态,ManualResetEvent也就可以同时唤醒多个线程继续执行。

本质上AutoResetEvent.Set()方法相当于ManualResetEvent.Set()+ManualResetEvent.Reset();

因此AutoResetEvent一次只能唤醒一个线程,其他线程还是堵塞

生动示例

用一个三国演义的典故来写段示例代码:

话说曹操率领80W大军准备围剿刘备和孙权,面对敌众我寡的情况,诸葛亮与周瑜想到了一个妙计,用装满火药桶的大船去冲击曹操连在一起的战船,计划都安排好了,可谓“万事俱备 只欠东风”。

 
01usingSystem;
02usingSystem.Collections.Generic;
03usingSystem.Linq;
04usingSystem.Text;
05usingSystem.Threading;
06  
07namespaceTest
08{
09    classProgram
10    {
11        //默认信号为不发送状态
12        privatestaticManualResetEvent mre = newManualResetEvent(false); 
13  
14        staticvoidMain(string[] args)
15        {
16            EastWind wind =newEastWind(mre);
17            //启动东风的线程
18            Thread thd =newThread(newThreadStart(wind.WindComming));
19            thd.Start();
20  
21            mre.WaitOne();//万事俱备只欠东风,事情卡在这里了,在东风来之前,诸葛亮没有进攻
22  
23            //东风到了,可以进攻了
24            Console.WriteLine("诸葛亮大吼:东风来了,可以进攻了,满载燃料的大船接着东风冲向曹操的战船");
25            Console.ReadLine(); 
26        }
27    }
28  
29    /// <summary>
30    /// 传说中的东风
31    /// </summary>
32    classEastWind
33    {
34        ManualResetEvent _mre;
35  
36        /// <summary>
37        /// 构造函数
38        /// </summary>
39        /// <param name="mre"></param>
40        publicEastWind(ManualResetEvent mre)
41        {
42            _mre = mre;
43        }
44  
45        /// <summary>
46        /// 风正在吹过来
47        /// </summary>
48        publicvoidWindComming()
49        {
50            Console.WriteLine("东风正在吹过来");
51            for(inti = 0; i <= 5; i++)
52            {
53                Thread.Sleep(500);
54                Console.WriteLine("东风吹啊吹,越来越近了...");
55            }
56            Console.WriteLine("东风终于到了");
57  
58            //通知诸葛亮东风已到,可以进攻了,通知阻塞的线程可以继续执行了
59            _mre.Set();
60        }
61    }
62  
63}

运行结果: