Home > Refactorings > The Lock to Try/Finally refactoring

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/Finally refactoring can help you to automate this task.

The refactoring produces the following result once it is applied:

CodeRush Lock to Try/Finally result

Now you can modify the code as required, for instance:

CodeRush Lock to Try/Finally modified code

This code does not have issues as with the lock statement mentioned above.

—–
Products: CodeRush Pro
Versions: 12.1 and up
VS IDEs: 2008 and up
Updated: Aug/28/2012
ID: R065

Similar Posts: