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 the use of the process in order to avoid acquiring the lock because of the exception, the lock cannot be released, Therefore, you need to release the lock (Monitor.Exit ()) in the finally{} structure after try{} catch () {}.
2.Monitor Common Properties and methods:
Enter (object) to acquire an exclusive lock on the specified object.
Exit (object) frees exclusive locks on the specified object.
Isentered determines whether the current thread retains the specified object lock.
Pulse notifies the thread in the waiting queue to lock the object state changes.
PulseAll notifies all waiting thread object state changes.
TryEnter (object) attempts to acquire an exclusive lock on the specified object.
TryEnter (object, Boolean) attempts to acquire an exclusive lock on the specified object and automatically sets a value indicating 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 candy that encapsulates the monitor object, and adds a mutex to object, which, when a process enters this code, adds a mutex to the object, and when other B processes enter the Code section, does the object have a lock? If a lock continues to wait for the a process to run out of the code snippet and unlock the object, the B process is able to get the object object to lock it and access the code snippet.
The monitor object structure for the 2.Lock keyword encapsulation is as follows:
Try
{
monitor.enter (obj);
DoSomething ();
}
catch (Exception ex)
{
}
finally
{
monitor.exit (obj);
}
3. Locked objects should be declared as private static object obj = new Object (), and try not to use public variables and strings, this, value types.
The difference between monitor and lock
1.Lock is the syntax candy for monitor.
2.Lock can only be locked for reference types.
3.Monitor is capable of locking value types, essentially boxing a value type when Monitor.Enter (object).
4.Monitor has some other features as well.