Pages

Saturday, February 13, 2010

C# lock, is it good to use?

Often .NET C# programmers are accustomed with writing the following code block:

lock(someObject)
{
/// code here...
}

But what happens when the compiler sees the above code? It simply emits the code below:















The above code guarantees that the lock is released i.e. the monitor is released no matter even an exception occurs within the try block. That means the data the code might be manipulating within the try block might be corrupted. And corrupted data is prone to more corruption when the program keeps proceeding further, this is really bad for the user. So it is better to use the below pattern,

Monitor.Enter()
/// your code here...
Monitor.Exit()

By doing this you are at least guaranteed that you prevent corruption of data and fail fast. Failing fast is good, you get to the root cause of the problem directly and fix it quicker.

Avoiding Lock is good not just because of the corruption of data scenario, code using "try, finally" is a perf hit. Remember try, catch, finally is an over-head unless it is used in the right place.

1 comment:

@VELU said...

so true and one more scenario worth mentioning is *exception handler can encounter an exception*
(http://blogs.msdn.com/oldnewthing/archive/2005/03/17/397468.aspx)