The Lock to Try/Finally refactoring

August 27th, 2012

Locking is essential in programs with multi-threading. It restricts code from being executed by more than one thread at the same time. The lock statement gets the exclusive monitor for an object and ensures that no other thread can access the object until the lock is released.

The lock statement automatically generates exception safe code, and in fact it is a syntactic shortcut for a call to the methods Monitor.Enter(obj) and Monitor.Exit(obj) with a try/finally block. However, if the thread is aborted after the lock is acquired but before entering the try block, the lock will not be released. Also, bear in mind that the Monitor.Enter() waits to acquire the lock forever which may introduce a possible deadlock condition.

To avoid these issues with the lock statement, it is better either to use different overloads of the Monitor.Enter() call which take additional arguments, such as amount of time or a number of milliseconds to wait while trying to obtain a lock, or use the Monitor.TryEnter() call which lets you specify a timeout for an operation. But before you can use any of these workarounds, you need to convert the lock statement into its equivalent code. The Lock to Try/Finallyrefactoring can help you to automate this task.