Csharp/C#教程: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."); } }

结果如下

C# ManualResetEvent用法详解

过程:

该示例以信号状态ManualResetEvent(false即传递给构造函数的)开头。三个线程,每个线程在调用其WaitOne方法时被阻止。当用户按Enter键时,该示例调用Set方法,该方法释放所有三个线程,使其继续执行。

再次按”enter”键,此时ManualResetEvent在调用Reset方法之前,一直保持终止状态,因此这些线程在调用WaitOne方法时不会被阻止,而是运行到完成。即对应上述(收到信号时必须手动重置该事件)

再次按enter键将导致该示例调用Reset方法,并启动一个线程,该线程在调用WaitOne时将被阻止。按enter键,最后一次调用Set以释放最后一个线程,程序结束。

如果还不是很清楚可以进行单步调试,这样就能明白了!

文章参考MSDN:ManualResetEventClass

您可能感兴趣的文章:C#ManualResetEvent使用方法详解C#中ManualResetEvent用法详解

标签: set al

C# OleDbDataReader快速数据读取方式(3种)

UGUI实现4位验证码输入

上述就是C#学习教程:C# ManualResetEvent用法详解分享的全部内容,如果对大家有所用处且需要了解更多关于C#学习教程,希望大家多多关注—计算机技术网(www.ctvol.com)!

本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。

ctvol管理联系方式QQ:251552304

本文章地址:https://www.ctvol.com/cdevelopment/903969.html

(0)
上一篇 2021年10月21日
下一篇 2021年10月21日

精彩推荐