Monitor object
The (object) method is to acquire the lock, and the (object) method is to release the lock. These are the two most commonly used methods of Monitor. Of course, in order to avoid the lock being unable to be released due to exceptions after obtaining the lock, it is necessary to release the lock in the finally{} structure after try{} catch(){}.
Common properties and methods:
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.
Pulse Notifies changes to the state of thread locked object in the waiting queue.
PulseAll Notifies all waiting thread object state changes.
TryEnter(Object) Attempt to obtain the exclusive lock of the specified object.
TryEnter(Object, Boolean) tries 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 reacquisitions the lock.
Lock keywords
The keyword is actually a syntax sugar. It encapsulates the Monitor object and adds a mutex to the object. When process A enters this code segment, it will add a mutex to the object object. At this time, other B processes enter this code segment to check whether the object has a lock? If there is a lock, continue to wait for process A to complete the code segment and unlock the object object. Process B can obtain the object object and add a lock to it and access the code segment.
The Monitor object structure of keyword encapsulation is as follows:
try
{
(obj);
dosomething();
}
catch(Exception ex)
{
}
finally
{
(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
It is the syntactic sugar of Monitor.
Locks can only be added to reference types.
It is able to lock the value type, which is essentially boxing the value type when (object).
There are some other features.
Code example in this article:
class Program
{
private static object obj = new object();
public void LockSomething()
{
lock (obj)
{
dosomething();
}
}
public void MonitorSomeThing()
{
try
{
(obj);
dosomething();
}
catch(Exception ex)
{
}
finally
{
(obj);
}
}
public void dosomething()
{
//Do specific things
}
}