The Monitor class Controls access to an object by granting an object lock to a single thread. Object locks provide the ability to restrict access to code blocks (often called critical sections). When a thread owns a lock on an object, no other thread can acquire the lock. You can also use Monitor to ensure that no other thread is allowed to access the section of the application code that is being executed by the owner of the lock, unless another thread is executing the code with another locked object.
Monitor can be equivalent to lock effect by combination of Enter and exit functions
1 Monitor.Enter (obj); 2 // ... 3 monitor.exit (obj); 4 5 Lock (obj) 6 {7 // ... 8 }
Object Lock equivalent
Unlike lock, monitor is more flexible and can be wait/pulse to create synchronization management between threads. The thread currently acquired to the lock (TA) passes the wait function, releasing control of the lock and suspending the current thread to a blocking state. At this point other threads can compete for lock resources (assuming TB acquires locks in many threads). TA will only be able to re-enter the ready state and re-compete for lock resources if it receives a TB pulse signal.
Note that the Pulse function is the first in the notification current waiting queue, and PulseAll is the thread that notifies all waiting queues.
1Thread Th2 =NewThread (() =2 {3 Lock(Aysnclock)4 {5Console.WriteLine ("Th2 Enter would wait");6 monitor.wait (aysnclock);7Console.WriteLine ("Th2 Continue");8 }9 });TenThread Th3 =NewThread (() = One { A Lock(Aysnclock) - { -Console.WriteLine ("Th3 Enter would wait"); the monitor.wait (aysnclock); -Console.WriteLine ("Th3 Continue"); - } - }); +Thread Th1 =NewThread (() = - { +Thread.Sleep (Timespan.fromseconds (1)); A Lock(Aysnclock) at { -Console.WriteLine ("Th1 Enter would pulseall"); -Console.WriteLine ($"Th1 tell:th2 State: [{Th2. ThreadState}]"); -Console.WriteLine ($"Th1 tell:th3 State: [{th3. ThreadState}]"); - //Monitor.pulseall (aysnclock); - Monitor.pulse (aysnclock); inConsole.WriteLine ($"Th1 tell:th2 State: [{Th2. ThreadState}]"); -Console.WriteLine ($"Th1 tell:th3 State: [{th3. ThreadState}]"); toConsole.WriteLine ("Th1 Exit"); + } -Console.WriteLine ($"Th1 tell:th2 State: [{Th2. ThreadState}]"); theConsole.WriteLine ($"Th1 tell:th3 State: [{th3. ThreadState}]"); * }); $ Panax Notoginseng Th1. Start (); - Th2. Start (); the Th3. Start (); +Console.readkey ();
Using the Pulse Result:
Th2, th3 only one execution
Using PulseAll results:
Th2, Th3 are executed
[. NET multithreading] Monitor