Development With A Dot

Blog on development in general, and specifically on .NET

The lock Statement

Experienced multithreading developers may have wondered what is the relation between the lock keyword and the System.Threading.Monitor class. Well, as it happens, they are exactly the same:

 

lock (instance)

{

    //do something

}

 

is exactly equal to:

 

try

{

    Monitor.Enter(instance);

}

finally

{

    Monitor.Exit(instance);

}

 

Bear in mind that the finally clause is necessary so that the lock is released.

Make sure you never lock on the object instance, but on an inner field instead, because the .NET Framework may also need to lock the instance, which may lead to a deadlock.

Comments

Joe Chung said:

The Monitor.Enter should be before the try-catch, not within it.

# October 26, 2008 5:59 PM
Leave a Comment

(required) 

(required) 

(optional)

(required)