Why is locking a type considered very bad?
For example, lock(typeof(DateTime)) I understand that 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.
Why is locking a type considered very bad? For example, lock(typeof(DateTime)) I understand that
Share
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.)