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.

                             

1 Comment

Comments have been disabled for this content.