This excerpt from the note: https://www.cnblogs.com/zhili/archive/2012/07/23/Event_Constructor.html , learning about the recording for subsequent lookup.
Speaking in front of the main thread synchronization is a user-mode (CLR Via C # book is so defined, the book when it comes to thread synchronization in two ways: First, the user configuration mode Second, the kernel mode structure), for kernel-mode configuration (refer to configuration of the operating system kernel objects), we use the .NET Framework class
As AutoResetEvent, Semaphore thread synchronization methods to achieve, in fact, its interior is call the operating system kernel object to implement thread synchronization, this time it will be thread into kernel code from managed code. The user configuration mode, because there is no operating system kernel object to call, so the thread will only use
Managed code execution on households.
A, WaitHandle base class Introduction
System.Threading provides a namespace WaitHandle abstract base class, such a package is a Windows kernel object handle (handle can be understood as a marked instance of the digital object,
We can find information specific depth understanding, the understanding presented here just handle is also very important).
Offers classes derived from WaitHandle class in the .NET Framework, is their inheritance:
WaitHandle
EventWaitHandle
AutoResetEvent
ManualResetEvent
Semaphore
Mutex
When we use a constructor to instantiate the AutoResetEvent, the ManualResetEvent, Semaphore, the Mutex when objects of these classes, which are internal or CreateEvent calls the Win32 function CreateEvent
Alternatively or CreateSemaphore CreateMutex function, the function call returns the handle value are stored in the field SafeWaitHandle WaitHandle base class definition.
Second, the event (Event) class that implements the Thread Synchronization
2.1 AutoResetEvent (auto-reset event)
2.1.1 First talk AutoResetEvent class constructor, which is defined as:
public AutoResetEvent(bool initialState);
An initial state with a constructor type bool AutoResetEvent set state of the object. If the initial state of the object to AutoResetEvent want to terminate the incoming bool value of true;
To set up a non-termination, incoming bool is false.
2.2.2WaitOne method definition:
public virtual bool WaitOne(int millisecondsTimeout);
The method used to block the thread, when the interval signal is not received in a specified time, returns false.
Set call signaling method to release the waiting thread.
In the course of WaitOne methods and Set methods are in pairs:
For blocking a thread, waiting for the signal;
To release a waiting thread (that is calling the set method to send a signal, received signal WaitOne this time, on the release of the blocked thread, the thread can continue to run.)
WaitOne thread through method calls AutoResetEvent to wait for a signal, if the object is a non-termination AutoResetEvent state, the thread is blocked until the thread calls the Set method to recover the thread of execution;
If AutoResetEvent is terminated state, the thread is not blocked, this time AutoResetEvent the immediate release and return to a non-thread termination status (one state pointed out that there is a thread in the use of resources).
The following code demonstrates the use of AutoResetEvent:
class Program { // Create Object public static the AutoResetEvent AutoResetEvent = new new the AutoResetEvent ( to false ); static void the Main ( String [] args) { #region thread synchronization: AutoResetEvent using Console.WriteLine ( " the Main Thread Start RUN AT: " + the DateTime .Now.ToLongTimeString ()); the thread thread = new new the thread (WaitOneMethod); Thread.Start (); // block the main thread 3 seconds the Thread.Sleep ( 3000 ); //释放线程 autoResetEvent.Set(); Console.Read(); #endregion } /// <summary> /// WaitOne方法 /// </summary> public static void WaitOneMethod() { autoResetEvent.WaitOne(); Console.WriteLine("Method restart run at: " + DateTime.Now.ToLongTimeString()); } }
Results are as follows:
If creating an object, turning it into a public static AutoResetEvent autoResetEvent = new AutoResetEvent (true);, the output of time to see is the same. Because the set to True, it indicates that at this time
Already terminated the state. Thus, autoResetEvent.Set () can be interpreted as state autoResetEvent set to the final state, thus releasing the thread.
WaitOne method used above is not with arguments, which means unlimited block threads until it receives an event (to send a signal through the Set method).
By bool WaitOne (int millisecondsTimeout), when a timeout, even if the thread did not receive the signal sent by the Set, will no longer block the thread and let it continue to run, but the value is not the same WaitOne method returns:
When the signal is received Set the return value is True, otherwise the return value is false.
The following code demonstrates WaitOne (millisecondsTimeout) use:
class Program { // create objects public static AutoResetEvent AutoResetEvent = new new AutoResetEvent ( false ); static void Main ( String [] args) { #region thread synchronization: WaitOne (millisecondsTimeout) using Console.WriteLine ( " Main Start the Thread RUN AT: " + DateTime.Now.ToLongTimeString ()); the thread thread = new new the thread (WaitOneTimeoutMethod); Thread.Start (); // block the main thread 3 seconds the Thread.Sleep ( 3000); //释放线程 autoResetEvent.Set(); Console.Read(); #endregion } /// <summary> /// WaitOneTimeout方法 /// </summary> public static void WaitOneTimeoutMethod() { if (autoResetEvent.WaitOne(2000)) { Console.WriteLine("Get signal to work."); Console.WriteLine("Method restart run at: " + DateTime.Now.ToLongTimeString()); } else { Console.WriteLine("Time out to work."); Console.WriteLine("Method restart run at: " + DateTime.Now.ToLongTimeString()); } } }
Results are as follows:
If the Thread.Sleep (3000); set Thread.Sleep (1000) ;, this time thread will receive a Set signal sent over, the result will be a Get signal to work, the time difference of only one second.
2.2 ManualResetEvent (manual reset event)
ManualResetEvent and AutoResetEvent to use very similar in that they are derived from EventWaitHandle class, but they are still some differences:
2.2.1AutoResetEvent for the termination state (true), if the calling thread WaitOne method, then the thread is not blocked. At this point AutoResetEvent immediately release the thread and return to the non-terminating state (false),
After that if the thread calling WaitOne method again, then thread will be blocked. (Note: WaitOne calling method for automatically changing the state, the initial state is only valid when the final state.)
2.2.2ManualResetEvent for the termination state (true), if the calling thread WaitOne method, then the thread is not blocked. This ManualResetEvent thread will be released immediately but will not return to the non-termination state (false),
Unless we manually change the status to terminate the state (false), otherwise after this method if the calling thread WaitOne again, then the thread will not be blocked.
The following code shows the difference between the two:
class Program { //创建对象 public static AutoResetEvent autoResetEvent = new AutoResetEvent(false); public static ManualResetEvent manualResetEvent = new ManualResetEvent(false); static void Main(string[] args) { #region 线程同步:ManualResetEvent的使用 Console.WriteLine("Main thread start run at: " + DateTime.Now.ToLongTimeString()); Thread threadAuto = new Thread(AutoResetEventMethod); threadAuto.Start(); autoResetEvent.Set(); threadAuto = new Thread(AutoResetEventMethod); threadAuto.Start(); Thread threadManual = new Thread(ManualResetEventMethod); threadManual.Start(); manualResetEvent.Set(); threadManual = new Thread(ManualResetEventMethod); threadManual.Start(); Console.Read(); #endregion } /// <summary> /// AutoResetEvent方法 /// </summary> public static void AutoResetEventMethod() { autoResetEvent.WaitOne(); Console.WriteLine("Autoresetevent method restart run at: " + DateTime.Now.ToLongTimeString()); } /// <summary> /// ManualResetEvent方法 /// </summary> public static void ManualResetEventMethod() { manualResetEvent.WaitOne(); Console.WriteLine("Manualresetevent method restart run at: " + DateTime.Now.ToLongTimeString()); } }
Results are as follows:
Cross-process synchronization between 2.3
Kernel-mode configuration can achieve different processes on the same machine in the thread synchronization, so you can use AutoResetEvent to implement this feature. At this point the need for AutoResetEvent be named, but AutoResetEvent provides only a constructor with a parameter, how to achieve it?
Way is still there, because AutoResetEvent inherited from EventWaitHandle class, EventWaitHandle class has multiple constructors.
In addition to creating objects AutoResetEvent previous methods, but also by EventWaitHandle autoEvent = new EventWaitHandle (false, EventResetMode.Auto, "My"); AutoResetEvent to construct the object in such a manner, this embodiment specifies the name.
The following code demonstrates cross-process synchronization between threads:
The first process code:
class Program { // Create Object public static the EventWaitHandle autoEventFirst = new new the EventWaitHandle ( to false , EventResetMode.AutoReset, " First " ); public static the EventWaitHandle autoEventSecond = new new the EventWaitHandle ( to false , EventResetMode.AutoReset, " Second " ); static void the Main ( String [] args) { #region thread synchronization: cross-process synchronization between threads Console.WriteLine ( "Start the Thread main RUN AT First: " + DateTime.Now.ToLongTimeString ()); the Thread the Thread = new new the Thread (EventWaitHandleMethod); Thread.start (); // In order to have time to start another process Thread.Sleep ( of 15,000 ); autoEventFirst.Set (); autoEventSecond.Set (); Console.Read (); #endregion } /// <Summary> /// the EventWaitHandle method /// </ Summary> public static void EventWaitHandleMethod () { autoEventFirst.WaitOne(); Console.WriteLine("First method start at:" + DateTime.Now.ToLongTimeString()); } }
The second process code:
class Program { //创建对象 public static EventWaitHandle autoEventSecond = new EventWaitHandle(false, EventResetMode.AutoReset, "Second"); static void Main(string[] args) { Console.WriteLine("Second main thread start run at: " + DateTime.Now.ToLongTimeString()); Thread thread = new Thread(EventWaitHandleMethod); thread.Start(); Console.Read(); } /// <summary> /// EventWaitHandle方法 /// </summary> public static void EventWaitHandleMethod() { autoEventSecond.WaitOne(); Console.WriteLine("Second method start at:" + DateTime.Now.ToLongTimeString()); } }
Results are as follows:
From the results, autoEventSecond.Set first process (); after the signal is issued, the second process can receive and release the thread.