开发者

.net thread safety

开发者 https://www.devze.com 2022-12-25 05:20 出处:网络
Why is locking a type considered very bad? For example, lock(typeof(DateTime)) I understand tha开发者_JAVA百科t static methods of any class in .net is considered thread safe, and that instance members

Why is locking a type considered very bad? For example, lock(typeof(DateTime)) I understand tha开发者_JAVA百科t static methods of any class in .net is considered thread safe, and that instance members are not. So it isn't necessary to lock DateTime while you are using it. The book I am reading doesn't explain why it is bad it just says it is. Any explanation will be great.


The CLR maintains a single instance of each type for each AppDomain (and as Joe points out in his answer, sometimes they are even shared across a broader context).

Since you don't control access to types, you can find yourself unintentionally blocking or being blocked by completely unrelated code that also locks on your type.

Instead, you should usually lock on private instances that are in the same class as the operation (or related operations) you want to lock so that you can control what the lock affects and blocks. (Though there are also cases where it makes sense to lock on some well-known synchronization object that is intended to be used across different objects.)


From MSDN:

The lock keyword marks a statement block as a critical section by obtaining the mutual-exclusion lock for a given object, executing a statement, and then releasing the lock. This statement takes the following form:

So basically you are supposed to lock an object. So if you want to have a lock you should have a specific object that you are locking, for example a container such as a HashTable or a shared object specifically used for locking.

By locking the result of typeof(DateTime) you are saying that no other object can put a lock on the type. This is too coarse-grained of a lock - in other words, your code should be able to lock another DateTime object in some other place in the code, but with your method that will not be possible.


Apart from the reasons already mentioned, a Type object can be shared across different AppDomains within the same process. Therefore code running in a different AppDomain could deadlock your app.

There's some discussion of this here.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号