Lock vs Monitor

lock Statement

The lock keyword marks a statement block as a critical section by obtaining the mutual-exclusion lock for a given object, executing a statement, and then releasing the lock.

The lock keyword ensures that one thread does not enter a critical section of code while another thread is in the critical section. If another thread tries to enter a locked code, it will wait, block, until the object is released.

The section Threading (C# and Visual Basic) discusses threading.

The lock keyword calls Enter at the start of the block and Exit at the end of the block. A ThreadInterruptedException is thrown if Interrupt interrupts a thread that is waiting to enter a lock statement.

In general, avoid locking on a public type, or instances beyond your code’s control. The common constructs lock (this), lock (typeof (MyType)), and lock (“myLock”) violate this guideline:

lock (this) is a problem if the instance can be accessed publicly.

lock (typeof (MyType)) is a problem if MyType is publicly accessible.

lock(“myLock”) is a problem because any other code in the process using the same string, will share the same lock.

Best practice is to define a private object to lock on, or a private static object variable to protect data common to all instances. You can’t use the await keyword in the body of a lock statement.

Monitor Class

Provides a mechanism that synchronizes access to objects.

The Monitor class controls access to objects by granting a lock for an object to a single thread. 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 that lock. You can also use Monitor to ensure that no other thread is allowed to 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.

Monitor has the following features:

> It is associated with an object on demand.

> It is unbound, which means it can be called directly from any context.

> An instance of the Monitor class cannot be created.

The following information is maintained for each synchronized object:

> A reference to the thread that currently holds the lock.

> A reference to a ready queue, which contains the threads that are ready to obtain the lock.

> A reference to a waiting queue, which contains the threads that are waiting for notification of a change in the state of the locked object.

A lock statement is equivalent to:

Monitor.Enter(myObject);
try
{
}
finally
{
   Monitor.Exit(myObject);
}
Categories: C# Tags: ,
%d bloggers like this: