ManualResetEven使用的最清楚说明c#
理解ManualResetEvent,以及如何使用。api
官方介绍:https://docs.microsoft.com/en-us/dotnet/api/system.threading.manualresetevent?view=netframework-1.1函数
一个线程同步事件 ,经过发信号来控制线程来控制 是否有权限访问 资源this
初始化实例,而且指明信号的初始状态 。线程
private static ManualResetEvent mre = new ManualResetEvent(false);
true:表示线程能够访问资源 ,就是能够无视waitone里的等待3d
false:表示线程若是碰到waitone的时候 ,就要暂停,等主线程来控制 。code
好比以下demo中,主线程调用线程执行如下方法时,若是默认是false,则只会输入***starts and calls mre.WaitOne() 而没有 ___ends的输出,由于默认是false ,线程中的waitone()会阻止线程的继续访问 。blog
private static void ThreadProc() { string name = Thread.CurrentThread.Name; Console.WriteLine(name + " starts and calls mre.WaitOne()"); mre.WaitOne(); Console.WriteLine(name + " ends."); }
将事件状态设置为“已发送信号”,容许被waitone() 阻止的一个或者多个线程进行执行线程中的代码。three
这个上面的demo中就会在调用mre.set()方法执行以后,会继续调用线程中的下面的___ends 的输出。事件
将事件状态设置为“没信号”,这样线程中执行waitone()的时候 ,就会阴止当前线程的执行。实现了和构造函数传入默认值false同样的效果,不过它能够在执行的过程当中,进行从新设置,表求又把线程调用组止了。
直接再次接收到set方法 。才会再次执行下面的访问 。
官方的demo
private static ManualResetEvent mre = new ManualResetEvent(false); static void Main(string[] args) { Console.WriteLine("\nStart 3 named threads that block on a ManualResetEvent:\n"); for (int i = 0; i <= 2; i++) { Thread t = new Thread(ThreadProc); t.Name = "Thread_" + i; t.Start(); } Thread.Sleep(500); Console.WriteLine("\nWhen all three threads have started, press Enter to call Set()" + "\nto release all the threads.\n"); Console.ReadLine(); mre.Set(); Thread.Sleep(500); Console.WriteLine("\nWhen a ManualResetEvent is signaled, threads that call WaitOne()" + "\ndo not block. Press Enter to show this.\n"); Console.ReadLine(); for (int i = 3; i <= 4; i++) { Thread t = new Thread(ThreadProc); t.Name = "Thread_" + i; t.Start(); } Thread.Sleep(500); Console.WriteLine("\nPress Enter to call Reset(), so that threads once again block" + "\nwhen they call WaitOne().\n"); Console.ReadLine(); mre.Reset(); // Start a thread that waits on the ManualResetEvent. Thread t5 = new Thread(ThreadProc); t5.Name = "Thread_5"; t5.Start(); Thread.Sleep(500); Console.WriteLine("\nPress Enter to call Set() and conclude the demo."); Console.ReadLine(); mre.Set(); } private static void ThreadProc() { string name = Thread.CurrentThread.Name; Console.WriteLine(name + " starts and calls mre.WaitOne()"); mre.WaitOne(); Console.WriteLine(name + " ends."); }
运行结果
我对个人文章负责,发现好多网上的文章 没有实践,都发出来的,让人走不少弯路,若是你在个人文章中遇到没法实现,或者没法走通的问题。能够直接在公众号《爱码农爱生活 》留言。一定会再次复查缘由。让每一篇 文章的流程都能顺利实现。