Why is “lock (typeof (MyType))” a problem?

前端 未结 6 2100
自闭症患者
自闭症患者 2020-12-14 00:00

MSDN gives the following warning about the lock keyword in C#:

In general, avoid locking on a public type, or instances beyond yo

6条回答
  •  渐次进展
    2020-12-14 00:56

    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.

提交回复
热议问题