什么时候锁定类型是个好主意?
从其他问题我可以看出锁定类型是一个坏主意。但这样做是可能的,所以我想知道这样做是否是一件坏事,为什么允许这样做?我假设必须有良好的用例来实现其目的,所以有人可以让我知道它们是什么吗?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
这几乎总是一个坏主意:
这是允许的,因为对于可以用作锁定对象的内容几乎没有任何限制。换句话说,它并没有被明确允许 - 只是 .NET 框架中没有任何代码不允许它。
《调试 Microsoft .NET 应用程序》一书包含 FxCop 规则
DoNotLockOnTypes
的源代码,如果您尝试执行此操作,该规则会向您发出警告。 (感谢克里斯蒂安.K)It's nearly always a bad idea:
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)要了解为什么这是一个坏主意,请查看文章 不要锁定类型对象。
这是允许的,因为语言/框架设计者决定能够锁定从
System.Object
派生的任何内容。没有人可以阻止它,因为System.Type
派生自System.Object
(与所有其他 .NET 类型一样)。采用这个签名:
编译器如何强制
o
不是System.Type
?您当然可以在运行时检查它,但这会对性能产生影响。当然,可能存在一些超级奇异的情况,人们可能需要锁定一种类型。也许 CLR 在内部执行此操作。
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 becauseSystem.Type
derives fromSystem.Object
(as every other .NET type).Take this signature:
How could a compiler enforce that
o
is noSystem.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.
许多糟糕的想法都进入了编程语言,因为没有语言设计者能够预测未来。人类创造的任何语言都会有缺陷。
一些示例:
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: