什么时候锁定类型是个好主意? [英] When is locking on types a good idea?

查看:56
本文介绍了什么时候锁定类型是个好主意?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

从其他问题中,我可以看到锁定类型是一个坏主意.但是有可能这样做,所以我想知道是否允许这样做是一件坏事?我假设为此目的必须有很好的用例,所以有人可以让我知道他们的意思吗?

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?

推荐答案

要了解为什么它通常不是一个好主意,请参阅文章

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

之所以允许,是因为语言/框架设计者决定能够锁定从System.Object派生的任何内容.没有人能阻止它,因为System.Type源自System.Object(与其他所有.NET类型一样).

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).

签署此签名:

void Foo(object o)

编译器如何强制o不是System.Type?您当然可以在运行时检查它,但这会影响性能.

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.

当然,在某些超奇特的情况下,可能需要锁定一种类型.也许CLR是在内部完成的.

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

这篇关于什么时候锁定类型是个好主意?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆