AutoResetEvent和ManualResetEvent之间的区别
在看他们的区别之前,先看看AutoResetEvent和ManualResetEvent的用法
ManualResetEvent用法
【转载】浅谈AutoResetEvent的用法
我下边列出一段小程序:
1
using System;
2
using System.Threading;
3
4
namespace AutoResetEvent_Examples
5
{
6
class MyMainClass
7
{
8
//初始的时候是没有信号的,这里的意思是指参数false
9
const int numIterations = 10; //重复次数设置多少都无所谓,为让大家看清楚设置了100
10
//static AutoResetEvent myResetEvent = new AutoResetEvent(false);
11
static ManualResetEvent myResetEvent = new ManualResetEvent(false);
12
static int number;
13
14
static void Main()
15
{
16
//创建并开始一个线程。
17
Thread myReaderThread = new Thread(new ThreadStart(MyReadThreadProc));
18
myReaderThread.Name = "ReaderThread";
19
myReaderThread.Start();
20
21
for (int i = 1; i <= numIterations; i++)
22
{
23
Console.WriteLine("Writer thread writing value: {0}", i);
24
number = i;
25
26
//发信号,说明值已经被写进去了。这里的意思是说Set是一个发信号的方法。
27
myResetEvent.Set();
28
29
//让每次循环当中有些间隔,没有其他作用,可以注释掉
30
Thread.Sleep(1000);
31
}
32
33
//终止阅读线程。
34
35
myReaderThread.Abort();
36
37
Console.ReadLine();
38
}
39
40
static void MyReadThreadProc()
41
{
42
while (true)
43
{
44
//在数据被作者写入之前不会被读者读取
45
//在上次读取之前至少有一次。
46
myResetEvent.WaitOne();
47
Console.WriteLine("{0} reading value: {1}", Thread.CurrentThread.Name, number);
48
}
49
}
50
}
51
}
52
using System;2
using System.Threading;3

4
namespace AutoResetEvent_Examples5
{6
class MyMainClass7
{8
//初始的时候是没有信号的,这里的意思是指参数false9
const int numIterations = 10; //重复次数设置多少都无所谓,为让大家看清楚设置了10010
//static AutoResetEvent myResetEvent = new AutoResetEvent(false);11
static ManualResetEvent myResetEvent = new ManualResetEvent(false);12
static int number;13

14
static void Main()15
{16
//创建并开始一个线程。17
Thread myReaderThread = new Thread(new ThreadStart(MyReadThreadProc));18
myReaderThread.Name = "ReaderThread";19
myReaderThread.Start();20

21
for (int i = 1; i <= numIterations; i++)22
{23
Console.WriteLine("Writer thread writing value: {0}", i);24
number = i;25

26
//发信号,说明值已经被写进去了。这里的意思是说Set是一个发信号的方法。27
myResetEvent.Set();28

29
//让每次循环当中有些间隔,没有其他作用,可以注释掉30
Thread.Sleep(1000);31
}32

33
//终止阅读线程。34

35
myReaderThread.Abort();36

37
Console.ReadLine();38
}39

40
static void MyReadThreadProc()41
{42
while (true)43
{44
//在数据被作者写入之前不会被读者读取45
//在上次读取之前至少有一次。46
myResetEvent.WaitOne();47
Console.WriteLine("{0} reading value: {1}", Thread.CurrentThread.Name, number);48
}49
}50
}51
}52

分别注销第10行和第11行代码,看看运行的结果就清楚了。他们运行的结果差别还是很大的。



浙公网安备 33010602011771号