Monitors (CLR locks)

9 07 2011

The CLR provides “monitors” as the managed code equivalent to critical regions and Win32’s critical sections. You call Monitor.Enter on an object to acquire the monitor, if another thread already holds that monitor the calling thread will block until the owning thread releases it. The owning thread releases the monitor by calling Monitor.Exit.

Don’t use ‘this’ as your object to lock on. It is better practice to explicitly manage and wall off your synchronization objects from the rest of the world. Using ‘this’ can make encapsulation difficult by exposing the implementation detail of your locking mechanism to clients of your object. In order to ensure that a thread always leaves the monitor you use a try / finally block so that the monitor is released even in the face of an exception.

Monitors are different from mutexes. A mutex works across multiple processes while monitors are for a single process. Monitors are a lot faster (~ 50 times faster) to acquire than mutexes because they are acquired in user mode, not kernel mode.

object monitorObj = new object();

Monitor.Enter(monitorObj);
try
{

}
finally
{
    Monitor.Exit(monitorObj);
}

This pattern is so common that C# provides syntactic sugar for it in the form of the lock statement.

object monitorObj = new object();

lock(monitorObj)
{
}

The same IL is emitted by the C# compiler in both of the cases above.

Advertisements

Actions

Information

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s




%d bloggers like this: