TICS Coding Standard Viewer 
TIOBE Software Quality Framework
Print-friendly version
©TIOBE Software www.tiobe.com
 
C# Coding Standard
Search

Rule:  6@119

Synopsis:Use a dedicated (private) lockable object as synchronization technique for parallel class instance (method) calls.
Language:C#
Severity Level:4
Category:Control flow


Description:
In C# code, you should never lock on "this", because "this" must be considered as a public type. Locking on "this" can cause very hard-to-find cross-threading bugs. Instead of using "lock (this)", a special-purpose private object must be created to lock on. This object's only reason for existence is to act as the object-to-lock, it should not be used for anything else.

Some references to motivate this rule. Note that the MSDN reference states that "lock (this) is a problem if the instance can be accessed publicly." (So, in fact, this new rule should only hold for publicly visible classes, but to keep things simple I would like to propose the rule without any restrictions). Note also that the MSDN reference lists similar problems for locking on "typeof(MyType)" when MyType is publicly accessible, and "myLock" when myLock is accessible to other code in the same process.

http://msdn.microsoft.com/en-us/library/c5kehkcz.aspx
http://www.thedotnetfrog.com/2008/04/04/lockthis-dont/
http://www.toolazy.me.uk/template.php?content=lock%28this%29_causes_deadlocks.xml