ManualResetEvent用法-飞外

ManualResetEvent 允许线程通过发信号互相通信。通常,此通信涉及一个线程在其他线程进行之前必须完成的任务。

public static ManualResetEvent mre = new ManualResetEvent(false);
ManualResetEvent建立时是把false作为start的初始状态,这个类用于通知另一个线程,让它等待一个或多个线程。注意,为了通知或监听同一个线程,所有的其它线程都能访问那个类。
等待线程这样写:
mre.WaitOne();
这将引起等待线程无限期的阻塞并等待类来通知。
发信号的线程应该这样:
mre.Set();
这样类就会被通知,值变成true,等待线程就会停止等待。在通知事件发生后,我们就可以使用下面语句把线程置于非终止状态,导致线程阻止:
mre.Reset();
一个测试的例子:

usingSystem;
usingSystem.Threading;
namespaceThreadingTester
{
classThreadClass
{
publicstaticManualResetEventmre=newManualResetEvent(false);
publicstaticvoidtrmain()
{
Threadtr=Thread.CurrentThread;
Console.WriteLine("thread:waitingforanevent");
mre.WaitOne();
Console.WriteLine("thread:gotanevent");
for(intx=0;x 10;x++)
{
Thread.Sleep(1000);
mre.WaitOne();
Console.WriteLine(tr.Name+":"+x);
}
}
staticvoidMain(string[]args)
{
Threadthrd1=newThread(newThreadStart(trmain));
thrd1.Name="thread1";
thrd1.Start();
for(intx=0;x 10;x++)
{
Thread.Sleep(900);
Console.WriteLine("Main:"+x);
if(5==x)mre.Set();
if(6==x)mre.Reset();
if(8==x)mre.Set();
}
while(thrd1.IsAlive)
{
Thread.Sleep(1000);
Console.WriteLine("Main:waitingforthreadtostop");
}
}
}
}运行的结果为:
thread: waiting for an event
Main:0
Main:1
Main:2
Main:3
Main:4
Main:5
thread: got an event
Main:6
Main:7
Main:8
thread1: 0
Main:9
thread1: 1
Main: waiting for thread to stop
thread1: 2
Main: waiting for thread to stop
thread1: 3
Main: waiting for thread to stop
thread1: 4
Main: waiting for thread to stop
thread1: 5
Main: waiting for thread to stop
thread1: 6
Main: waiting for thread to stop
thread1: 7
Main: waiting for thread to stop
thread1: 8
Main: waiting for thread to stop
thread1: 9
Main: waiting for thread to stop