Monitor Object
The 1.monitor.enter (object) method is to acquire the lock, the Monitor.Exit (object) method is to release the lock, which is the most commonly used two methods of Monitor, of course, in order to avoid acquiring locks after the lock because of the exception, the lock cannot be released, Therefore, you need to release the lock (Monitor.Exit ()) in the structure body of finally{} after try{} catch () {}.
Common properties and methods for 2.Monitor:
Enter (object) acquires an exclusive lock on the specified object.
Exit (object) releases the exclusive lock on the specified object.
isentered determines whether the current thread retains the specified object lock.
Pulse notifies a thread in the waiting queue of a change in the state of the locked object.
PulseAll notifies all waiting thread object state changes.
TryEnter (Object) An attempt was made to get an exclusive lock on the specified object.
TryEnter (Object, Boolean) Attempts to get an exclusive lock on the specified object and automatically sets a value that indicates whether the lock was obtained.
Wait (object) frees the lock on the object and blocks the current thread, Until it acquires the lock again.
Lock keyword
The 1.Lock keyword is actually a syntactic sugar that encapsulates the monitor object and adds a mutex to object, and when a process enters this snippet, the object object is given a mutex, while other B processes enter this snippet to check if the object has a lock? If a lock continues to wait until the a process finishes running the code snippet and unlocks the object, the B process is able to get the object objects to lock on it and access the code snippet.
The monitor object structure in the 2.Lock keyword package is as follows:
Try { monitor.enter (obj); DoSomething (); } Catch (Exception ex) { } finally { monitor.exit (obj); }
3. The locked object should be declared as private static object obj = new object (); Try not to use public variables and strings, this, and value types.
The difference between monitor and lock
1.Lock is the syntax sugar of monitor.
2.Lock can only be locked for reference types.
3.Monitor is able to lock a value type, essentially boxing a value type when Monitor.Enter (object).
4.Monitor has other features as well.
This article code example:
classProgram {Private Static Objectobj =New Object(); Public voidlocksomething () {Lock(obj) {dosomething (); } } Public voidmonitorsomething () {Try{monitor.enter (obj); DoSomething (); } Catch(Exception ex) {}finally{monitor.exit (obj); } } Public voiddosomething () {//to do something specific } }
Original: http://www.cnblogs.com/cuihongyu3503319/p/5730268.html
Turn: The difference analysis between monitor object and lock keyword in C #