When is locking on types a good idea?

你。 提交于 2019-12-11 02:39:23

问题


From other questions I can see that locking on types is a bad idea. But it is possible to do so, so I was wondering if it is such a bad thing to do why is it allowed? I am assuming there must be good use cases for its purpose so could someone let me know what they are please?


回答1:


To understand why it is a bad idea in general have a look at the article Don't lock type objects.

It is allowed because the language/framework designers decided to be able to take lock on anything that derives from System.Object. Nobody can prevent it because System.Type derives from System.Object (as every other .NET type).

Take this signature:

void Foo(object o)

How could a compiler enforce that o is no System.Type? You could of course check it at runtime, but this would have a performance impact.

And of course there might be super-exotic situations where one might need to lock on a type. Maybe the CLR does it internally.




回答2:


It's nearly always a bad idea:

  • Anyone can lock on the types from anywhere in the code, so you have no way to be sure that you won't get a deadlock without looking through all the code.
  • Locking on a type can even cause deadlocks across AppDomains. See Joe Duffy's article: Don't lock on marshal-by-bleed objects.

It's allowed because there are almost no restrictions on what you can use as your lock object. In other words, it wasn't specifically allowed - it's just that there isn't any code in the .NET framework that disallows it.

The book "Debugging Microsoft .NET Applications" has source code for an FxCop rule DoNotLockOnTypes that warns you if you try to do this. (thanks to Christian.K)




回答3:


Many bad ideas find their way into programming languages because no language designer can foretell the future. Any language created by humans will have warts.

Some examples:

  1. Hejlsberg wished (Original article: The A-Z of Programming Languages: C# - Computerworld) he had added non-nullable class references to C#. (I wish he had bitten off the const problem as well.)
  2. The C++ committee screwed up with valarray, and export, among numerous other minor and major regrets.
  3. Java's templates were a botch-job (OMG, type elision!) designed to avoid changing the VM, and by the time they realised the VM had to change anyway, it was too late to do the necessary rework.
  4. Python's scoping rules are a constant irritant that numerous attempts to improve it haven't really helped much (a little, but not much).


来源:https://stackoverflow.com/questions/8209243/when-is-locking-on-types-a-good-idea

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!