C# ManualResetEvent用法详解
ManualResetEvent表示线程同步事件,可以对所有进行等待的线程进行统一管理(收到信号时必须手动重置该事件)
其构造函数为:
publicManualResetEvent(boolinitialState);
参数initialState表示是否初始化,如果为true,则将初始状态设置为终止(不阻塞);如果为false,则将初始状态设置为非终止(阻塞)。
注意:如果其参数设置为true,则ManualResetEvent等待的线程不会阻塞。如果初始状态为false,则在Set调用方法之前,将阻止线程。
它只有两个方法
//将事件状态设置为终止状态,从而允许继续执行一个或多个等待线程。 publicboolSet(); //将事件状态设置为非终止,从而导致线程受阻。 publicboolReset(); //返回值:操作成功返回true,否则false
讲了这么多,看个例子理解一下
usingSystem;
usingSystem.Threading;
publicclassExample
{
//mreisusedtoblockandreleasethreadsmanually.Itis
//createdintheunsignaledstate.
privatestaticManualResetEventmre=newManualResetEvent(false);
staticvoidMain()
{
Console.WriteLine("\nStart3namedthreadsthatblockonaManualResetEvent:\n");
for(inti=0;i<=2;i++)
{
Threadt=newThread(ThreadProc);
t.Name="Thread_"+i;
t.Start();//开始线程
}
Thread.Sleep(500);
Console.WriteLine("\nWhenallthreethreadshavestarted,pressEntertocallSet()"+
"\ntoreleaseallthethreads.\n");
Console.ReadLine();
mre.Set();
Thread.Sleep(500);
Console.WriteLine("\nWhenaManualResetEventissignaled,threadsthatcallWaitOne()"+
"\ndonotblock.PressEntertoshowthis.\n");
Console.ReadLine();
for(inti=3;i<=4;i++)
{
Threadt=newThread(ThreadProc);
t.Name="Thread_"+i;
t.Start();
}
Thread.Sleep(500);
Console.WriteLine("\nPressEntertocallReset(),sothatthreadsonceagainblock"+
"\nwhentheycallWaitOne().\n");
Console.ReadLine();
mre.Reset();
//StartathreadthatwaitsontheManualResetEvent.
Threadt5=newThread(ThreadProc);
t5.Name="Thread_5";
t5.Start();
Thread.Sleep(500);
Console.WriteLine("\nPressEntertocallSet()andconcludethedemo.");
Console.ReadLine();
mre.Set();
//IfyourunthisexampleinVisualStudio,uncommentthefollowingline:
//Console.ReadLine();
}
privatestaticvoidThreadProc()
{
stringname=Thread.CurrentThread.Name;
Console.WriteLine(name+"startsandcallsmre.WaitOne()");
mre.WaitOne();//阻塞线程,直到调用Set方法才能继续执行
Console.WriteLine(name+"ends.");
}
}
结果如下
过程:
该示例以信号状态ManualResetEvent(false即传递给构造函数的)开头。三个线程,每个线程在调用其WaitOne方法时被阻止。当用户按Enter键时,该示例调用Set方法,该方法释放所有三个线程,使其继续执行。
再次按"enter"键,此时ManualResetEvent在调用Reset方法之前,一直保持终止状态,因此这些线程在调用WaitOne方法时不会被阻止,而是运行到完成。即对应上述(收到信号时必须手动重置该事件)
再次按enter键将导致该示例调用Reset方法,并启动一个线程,该线程在调用WaitOne时将被阻止。按enter键,最后一次调用Set以释放最后一个线程,程序结束。
如果还不是很清楚可以进行单步调试,这样就能明白了!
文章参考MSDN:ManualResetEventClass
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。
声明:本文内容来源于网络,版权归原作者所有,内容由互联网用户自发贡献自行上传,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任。如果您发现有涉嫌版权的内容,欢迎发送邮件至:czq8825#qq.com(发邮件时,请将#更换为@)进行举报,并提供相关证据,一经查实,本站将立刻删除涉嫌侵权内容。