Implementation of lock keyword

24 באפריל 2006

tags: ,
no comments

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!

Add comment
facebook linkedin twitter email