The MSDN documentation says that
public class SomeObject { public void SomeOperation() { lock(this) { //Access instance variables } } }
is "a problem if the instance can be accessed publicly". I’m wondering why? Is it because the lock will be held longer than necessary? Or is there some more insidious reason?
It is bad form to use
thisin lock statements because it is generally out of your control who else might be locking on that object.In order to properly plan parallel operations, special care should be taken to consider possible deadlock situations, and having an unknown number of lock entry points hinders this. For example, any one with a reference to the object can lock on it without the object designer/creator knowing about it. This increases the complexity of multi-threaded solutions and might affect their correctness.
A private field is usually a better option as the compiler will enforce access restrictions to it, and it will encapsulate the locking mechanism. Using
thisviolates encapsulation by exposing part of your locking implementation to the public. It is also not clear that you will be acquiring a lock onthisunless it has been documented. Even then, relying on documentation to prevent a problem is sub-optimal.Finally, there is the common misconception that
lock(this)actually modifies the object passed as a parameter, and in some way makes it read-only or inaccessible. This is false. The object passed as a parameter tolockmerely serves as a key. If a lock is already being held on that key, the lock cannot be made; otherwise, the lock is allowed.This is why it’s bad to use strings as the keys in
lockstatements, since they are immutable and are shared/accessible across parts of the application. You should use a private variable instead, anObjectinstance will do nicely.Run the following C# code as an example.
Console output