ManualResetEvent & AutoResetEvent

   参考资料:

  1. https://msdn.microsoft.com/en-us/library/system.threading.manualresetevent.aspx

  2. https://msdn.microsoft.com/en-us/library/system.threading.autoresetevent.aspx

  二者的区别,跑一下下边的程序就懂了。

   ManualResetEvent:通知一个或多个等待线程该事件已经发生。

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Text;
 5 using System.Threading;
 6 using System.Threading.Tasks;
 7 
 8 namespace Test01
 9 {
10     class Program
11     {
12         private static ManualResetEvent mre = new ManualResetEvent(false);
13 
14         static void Main(string[] args)
15         {
16             for (int i = 0; i < 3; i++)
17             {
18                 Thread thread = new Thread(ThreadProc);
19                 thread.Name = "Thread_" + i;
20                 thread.Start();
21             }
22 
23             Thread.Sleep(100);
24             Console.WriteLine("If you want to release all threads. Please press 'Enter'.");
25             Console.ReadLine();
26 
27             mre.Set();
28             Console.WriteLine("All threads have been released.");
29             mre.Reset();
30         }
31 
32         private static void ThreadProc()
33         {
34             string threadName = Thread.CurrentThread.Name;
35 
36             Console.WriteLine("Thread: " + threadName + " starts and begin WaitOne().");
37             mre.WaitOne();
38             Console.WriteLine("Thread: " + threadName + " gets the signal and ends.");
39         }
40     }
41 }
ManualResetEvent

 

   AutoResetEvent:通知一个等待线程该事件已经发生。

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Text;
 5 using System.Threading;
 6 using System.Threading.Tasks;
 7 
 8 namespace Test02
 9 {
10     class Program
11     {
12         private static AutoResetEvent are = new AutoResetEvent(false);
13 
14         static void Main(string[] args)
15         {
16             for (int i = 0; i < 3; i++)
17             {
18                 Thread thread = new Thread(ThreadProc);
19                 thread.Name = "Thread_" + i;
20                 thread.Start();
21             }
22 
23             Thread.Sleep(100);
24 
25             Console.WriteLine("Please press Enter to release the signal.");
26             Console.ReadLine();
27             are.Set();
28         }
29 
30         private static void ThreadProc()
31         {
32             string threadName = Thread.CurrentThread.Name;
33 
34             Console.WriteLine("Thread: " + threadName + " waits for AutoResetEvent.");
35             are.WaitOne();
36             Console.WriteLine("Thread: " + threadName + " gets the signal and is released.");
37             are.Set();
38         }
39     }
40 }
AutoResetEvent_1

 

posted @ 2015-12-03 16:16  motein  阅读(161)  评论(0编辑  收藏  举报