MSDN gives the following warning about the lock keyword in C#:
In general, avoid locking on a public
type, or instances beyond your code’s
control. The common constructs lock
(this), lock (typeof (MyType)), and
lock (“myLock”) violate this
guideline:* lock (this) is a problem if the instance can be accessed publicly. * lock (typeof (MyType)) is a problem if MyType is publicly accessible.
Yet it gives no solid reasoning for it. The lock(this) is explained here on SO. I’m interested in lock(typeof(MyType)) case. What is dangerous about it?
Thank you.
It’s dangerous because anything can take that lock so it’s difficult or impossible to prevent a deadlock situation.
There used to be an article on this (“Don’t Lock Type Objects!” a Dr. GUI article) in with some comments by Rico Mariani. Apparently the article is no longer directly available, but there are ‘mirrors’ floating around, including at http://bytes.com/topic/c-sharp/answers/249277-dont-lock-type-objects.
Here’s an excerpt: