DCSIMG
Implementation of lock keyword - Guy Burstein's Blog

Guy Burstein's Blog

Developer Evangelist @ Microsoft

News

Guy Burstein The Bu

Disclaimer
Postings are provided 'As Is' with no warranties and confer no rights.

Guy Burstein LinkedIn Profile

Implementation of lock keyword

The lock keyword can be used to ensure that a block of code runs to completion without interruption by other threads. This is accomplished by obtaining a mutual-exclusion lock for a given object for the duration of the code block.

the lock keyword is implemented with the Monitor class. For example:

lock (x)
{
   DoSomething();
}

Is equivalent to:

object obj = (object)x;
System.Threading.
Monitor.Enter(obj);
try
{
   DoSomething();
}
finally
{
   System.Threading.
Monitor.Exit(obj);
}

Using the lock keyword is generally preferred over using the Monitor class directly, both because lock is more concise, and because lock insures that the underlying monitor is released, even if the protected code throws an exception. This is accomplished with the finally keyword, which executes its associated code block regardless of whether an exception is thrown.

Enjoy!

Comments

No Comments