只读CultureInfo对象是线程安全的吗? [英] Are read-only CultureInfo objects thread-safe?

查看:126
本文介绍了只读CultureInfo对象是线程安全的吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

前言:我知道如何创建只读的CultureInfo对象.这不是问题,在这里已得到详细解答:

Preface: I know how to create a read-only CultureInfo object. That is not the question and it has been answered in detail here:

请注意,该问题的内容与此内容相似,但答案却完全不同.在考虑以重复另一个问题的方式结束该问题之前,请考虑以下事实:另一个问题中的答案中的没有一个回答了这个问题.

Note that the text of that question is similar to this one, but the answers are completely different. Before thinking about closing this question as a duplicate of the other one, please consider the fact that none of the answers in the other question answers this question.

我的问题:

访问只读CultureInfo对象的实例成员是否具有线程安全性?

有理由认为它是:

  • 如果不是,则使用CultureInfo.InvariantCulture的实例成员或CultureInfo.GetCultureInfo检索的对象将不是线程安全的,并且很多代码都会中断.

  • If it weren't, using instance members of CultureInfo.InvariantCulture or objects retrieved by CultureInfo.GetCultureInfo wouldn't be thread-safe, and a lot of code would break.

社区似乎是这样认为的(请参阅 Henk对这个答案的评论),但没有解释为什么.

The community seems to think so (see Henk's comment on this answer), but does not explain why.

有理由认为不是:

  • MSDN文档(不保证任何实例成员都是线程安全的." )

人们通常会混淆只读"和线程安全",尽管

People often confuse "read-only" and "thread-safe", although they are two different things.

推荐答案

更改对象时,线程安全是一个问题,所以问题是:您是在更改对象还是在CultureInfo内部发生了某些事情,可能更改其状态.

Thread safety is an issue when you are altering an object, so the question is: are you altering the object or does something happen inside the CultureInfo that could change its state.

MSDN 对此不是特别清楚:它只是显示有关线程安全性的默认通知.

MSDN isn't particularly clear about this: it just shows the default notice about thread-safety.

所以我们必须找出自己.幸运的是,可以通过参考源使用CultureInfo类.在那里,您会发现它将在方法开始时加载区域性数据,并将结果缓存在CultureInfo类中.

So we have to find out ourselves. Luckily, the CultureInfo class is made available through the reference source. There you will find it will load the culture data at the start of the method, and cache that result inside the CultureInfo class.

属性的初始化不是线程安全的.例如,参见 NumberFormat属性:它可以实例化由于并发调用导致两个实例.没有锁定!

The initialization of properties is not thread-safe. See for example the NumberFormat property: it can instantiate two instances due to concurrent calls. There is no locking!

在某些地方存在更多问题,例如再次出现NumberFormat属性,您可以在其中更改其属性.在该类中,它会检查它是否可写,因此,如果您使用默认区域性(只读区域性,如InvariantCulture),则不会出现线程安全问题.在所有其他情况下,我们不能认为它是线程安全的.

There are more problems at some places, for example the NumberFormat property again, where you can change its properties. Inside that class it checks if it is writable or not, so if you are using default cultures (the read-only ones, like InvariantCulture) there is no thread-safety issue. In all other cases we can't assume it is thread-safe.

结论:它们不是线程安全的.

Conclusion: they are not thread-safe.

这篇关于只读CultureInfo对象是线程安全的吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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