首页 > 代码库 > ManualResetEvent的使用
ManualResetEvent的使用
1 using System; 2 using System.Threading; 3 4 public class Example 5 { 6 // mre is used to block and release threads manually. It is 7 // created in the unsignaled state. 8 private static ManualResetEvent mre = new ManualResetEvent(false); 9 10 static void Main() 11 { 12 Console.WriteLine("\nStart 3 named threads that block on a ManualResetEvent:\n"); 13 14 for(int i = 0; i <= 2; i++) 15 { 16 Thread t = new Thread(ThreadProc); 17 t.Name = "Thread_" + i; 18 t.Start(); 19 } 20 21 Thread.Sleep(500); 22 Console.WriteLine("\nWhen all three threads have started, press Enter to call Set()" + 23 "\nto release all the threads.\n"); 24 Console.ReadLine(); 25 26 mre.Set(); 27 28 Thread.Sleep(500); 29 Console.WriteLine("\nWhen a ManualResetEvent is signaled, threads that call WaitOne()" + 30 "\ndo not block. Press Enter to show this.\n"); 31 Console.ReadLine(); 32 33 for(int i = 3; i <= 4; i++) 34 { 35 Thread t = new Thread(ThreadProc); 36 t.Name = "Thread_" + i; 37 t.Start(); 38 } 39 40 Thread.Sleep(500); 41 Console.WriteLine("\nPress Enter to call Reset(), so that threads once again block" + 42 "\nwhen they call WaitOne().\n"); 43 Console.ReadLine(); 44 45 mre.Reset(); 46 47 // Start a thread that waits on the ManualResetEvent. 48 Thread t5 = new Thread(ThreadProc); 49 t5.Name = "Thread_5"; 50 t5.Start(); 51 52 Thread.Sleep(500); 53 Console.WriteLine("\nPress Enter to call Set() and conclude the demo."); 54 Console.ReadLine(); 55 56 mre.Set(); 57 58 // If you run this example in Visual Studio, uncomment the following line: 59 //Console.ReadLine(); 60 } 61 62 63 private static void ThreadProc() 64 { 65 string name = Thread.CurrentThread.Name; 66 67 Console.WriteLine(name + " starts and calls mre.WaitOne()"); 68 69 mre.WaitOne(); 70 71 Console.WriteLine(name + " ends."); 72 } 73 } 74 75 /* This example produces output similar to the following: 76 77 Start 3 named threads that block on a ManualResetEvent: 78 79 Thread_0 starts and calls mre.WaitOne() 80 Thread_1 starts and calls mre.WaitOne() 81 Thread_2 starts and calls mre.WaitOne() 82 83 When all three threads have started, press Enter to call Set() 84 to release all the threads. 85 86 87 Thread_2 ends. 88 Thread_0 ends. 89 Thread_1 ends. 90 91 When a ManualResetEvent is signaled, threads that call WaitOne() 92 do not block. Press Enter to show this. 93 94 95 Thread_3 starts and calls mre.WaitOne() 96 Thread_3 ends. 97 Thread_4 starts and calls mre.WaitOne() 98 Thread_4 ends. 99 100 Press Enter to call Reset(), so that threads once again block101 when they call WaitOne().102 103 104 Thread_5 starts and calls mre.WaitOne()105 106 Press Enter to call Set() and conclude the demo.107 108 Thread_5 ends.109 */
原文来自:http://msdn.microsoft.com/zh-cn/library/system.threading.manualresetevent(v=vs.110).aspx?cs-save-lang=1&cs-lang=csharp#code-snippet-1
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。