Posts Tagged ‘Lock’

The Lock to Try/Finally refactoring

August 27th, 2012 Comments off

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.

Read more…