About the Monitor object in .NET framework

Object monitor plays a leading role in thread synchronization. Apart from its Enter and Exit methods (equivalent to opening and closing bracket pair after the lock keyword specifying synchronized code block), it offers two additional methods which are required to augment its synchronization functionality.

 

According to the documentation, Enter and Exit methods enclose a critical region, in which the object monitored is ensured of being accessed mutually exclusively by different threads.

 

A thread can relinquish the monitored object it owns by calling Monitor.Wait method, and all the other threads waiting on the object contend for it. DotNet thread mechanism requires the thread releasing the object should call Monitor.Pulse or Monitor.PulseAll to notify all waiting threads that the monitored object's status has been updated before calling the Monitor.Wait. Therefore, as for the code below, the Monitor.Pulse method call right before end of the the lock section is indespensible lest the blocked thread not be woken up.

 

 

using System; namespace ConsoleTest { class ThreadingTest { void DoCriticalJobs() { lock(this) { for (int i = 0; i < 10; i++) { Console.WriteLine("CriticalJob {0} on thread {1}", i, System.Threading.Thread.CurrentThread.ManagedThreadId); if (i == 4) { System.Threading.Monitor.Pulse(this); System.Threading.Monitor.Wait(this); } } System.Threading.Monitor.Pulse(this); /* this line is essential */ } } void ThreadEntry(object obj) { DoCriticalJobs(); } public void Test() { System.Threading.Thread thread1 = new System.Threading.Thread( new System.Threading.ParameterizedThreadStart(this.ThreadEntry)); System.Threading.Thread thread2 = new System.Threading.Thread( new System.Threading.ParameterizedThreadStart(this.ThreadEntry)); thread1.Priority = System.Threading.ThreadPriority.Normal; thread2.Priority = System.Threading.ThreadPriority.Normal; thread1.Start(); thread2.Start(); thread1.Join(); thread2.Join(); } } }

 

 

你可能感兴趣的:(thread,.net,object,Class,documentation,methods)