Are read-only CultureInfo objects thread-safe?

只愿长相守 提交于 2019-12-13 07:37:18

问题


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

  • CultureInfo thread safety

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.


My question:

Is it thread-safe to access instance members of a read-only CultureInfo object?

Reasons to assume that it is:

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

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

Reasons to assume that it isn't:

  • No such garantee is made in the MSDN documentation ("Any instance members are not guaranteed to be thread safe.")

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


回答1:


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 isn't particularly clear about this: it just shows the default notice about thread-safety.

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.

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!

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.



来源:https://stackoverflow.com/questions/36766649/are-read-only-cultureinfo-objects-thread-safe

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