Monitor object
1. monitor. the Enter (object) method is to obtain the lock, Monitor. the Exit (object) method is to release the lock, which is the two most commonly used methods of Monitor. Of course, to avoid the lock being released due to exceptions after the lock is obtained, therefore, you need to release the lock (Monitor. exit ()).
2. Common attributes and methods of Monitor:
Enter (Object) gets the 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.
The Pulse notifies the thread in the waiting queue of changing the status of the locked object.
PulseAll notifies all pending thread object status changes.
TryEnter (Object) attempts to obtain the exclusive lock of the specified Object.
TryEnter (Object, Boolean) attempts to obtain the exclusive lock on the specified Object, and automatically sets a value to indicate whether the lock has been obtained.
Wait (Object) releases the lock on the Object and blocks the current thread until it acquires the lock again.
Lock keyword 1. the Lock keyword is actually A syntactic sugar. It encapsulates the Monitor object and adds A mutex Lock to the object. When process A enters this code segment, it adds A mutex Lock to the object, when other B processes enter this code segment, check whether the object has a lock? If there is A lock, process B will continue to wait until process A finishes running the code segment and unlocks the object, so that process B can obtain the object and add the lock to it to access the code segment.
2. The structure of the Monitor object encapsulated by the Lock keyword 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 (); Do not use public variables and strings, this, and value types whenever possible.
Differences between Monitor and Lock
1. Lock is the syntactic sugar of Monitor.
2. Lock can only be applied to the reference type.
3. Monitor can lock the value type, which is essentially a boxed value type during Monitor. Enter (object.
4. Monitor has other functions.
Sample Code:
Class Program
{
Private static object obj = new object ();
Public void LockSomething ()
{
Lock (obj)
{
Dosomething ();
}
}
Public void MonitorSomeThing ()
{
Try
{
Monitor. Enter (obj );
Dosomething ();
}
Catch (Exception ex)
{
}
Finally
{
Monitor. Exit (obj );
}
}
Public void dosomething ()
{
// Perform specific tasks
}
}