Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
404 views
in Technique[技术] by (71.8m points)

c# - Why is "lock (typeof (MyType))" a problem?

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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:

The basic problem here is that you don't own the type object, and you don't know who else could access it. In general, it's a very bad idea to rely on locking an object you didn't create and don't know who else might be accessing. Doing so invites deadlock. The safest way is to only lock private objects.

But wait; it's even worse than all that. As it turns out, type objects are sometimes shared across application domains (but not across processes) in current versions of the .NET runtime. (This is generally okay since they're immutable.) That means that it's possible for ANOTHER APPLICATION running even in a different application domain (but in the same process) to deadlock your application by getting a lock on a type object you want to lock and never releasing it. And it would be easy to get access to that type object because the object has a name—the fully qualified name of the type! Remember that lock/SyncLock blocks (that's a polite word for hangs) until it can obtain a lock. It's obviously really quite bad to rely on a lock that another program or component can lock and cause you to deadlock.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...