Saturday, February 13, 2010

C# lock, is it good to use?

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

/// 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,

/// your code here...

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*