|Synopsis:||Use a dedicated (private) lockable object as synchronization technique for parallel class instance (method) calls.|
|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.