Why lock(this) is bad
My last column has generated more questions again:
I am reading your article, "Write code for a multithreaded world". It is very interesting.
Could you please go more detail about Locking the this object is always a bad idea?
The referenced article is here.
Well, the problem is one of how to manage the complexity involved with locks. When you say lock (this), the visibility of the object being locked matches the visibility of the class. So, if you have a public class, the object being locked is visible from everywhere.
Let's say you have a deadlock issue in your code. Well, if your locking objects are all private to a class you have done quite a bit to limit where you need to look. Chances are some method in your class acquires the lock, and then raises an event while holding the lock. The event handler may switch threads (through Control.Invoke) and that handler calls another method that tries to acquire the same lock.
It's still a tough problem, but there are a small number of ways to hurt yourself, and when you do, you've got a bounded set of code (that one class) where you need to look.
On the other hand, suppose a class is littered with lock(this) and you have a deadlock. Now, you need to search the entire codebase for lock constructs and examine each one to see if it's locking that object. Instead of one class, you could have hundreds of thousands of lines of code to search. It's a needle in a haystack, and the likelihood of finding the cause is the same.
So, prefer locking on a private member variable rather than locking this.