Monitor class: Thread Safety
April 10th, 2008
The Monitor class controls access to objects by granting a single thread a lock for an object. Object locks provide the ability to restrict access to a block of code, commonly called a critical section. While a thread owns the lock for an object no other thread can acquire the lock for the object. Additionally, the Monitor class can be used to ensure that no other thread can access a section of application code being executed by the lock owner, unless the other thread is executing the code using a different locked object.
I ever wondered what the difference between using a lock statement, versus using a Montior.Enter / Monitor.Exit clause is? Actually thereâs a few, but the main one is that a lock statement is inherently thread safe, where-as a Montior is not. So -
try {
Monitor.Enter(_lock);
DoThreadSafeCode();
} finally {
Monitor.Exit(_lock);
}
is essentially the same as -
lock (_lock) {
DoThreadSafeCode();
}





