CultureInfo的线程安全 [英] CultureInfo thread safety
问题描述
我有一个多线程的应用程序,它解析一些文本,它需要使用英语文化信息从这个文本解析数字。
所以,我不希望创建EngCulture每次我打电话解析功能。目前,我路过EngCulture作为一个参数,但我不开心的与此有关。
我要定义的EngCulture作为静态成员,因此将被线程共享。
MSDN文档中说,任何公共静态(在Visual Basic中的Shared )这种类型的成员都是线程安全的。所有实例成员不能保证是线程安全的。
我只是用下面的函数,所以我怎么会知道的TryParse是否使用EngCulture的任何实例成员与否?
公共静态的CultureInfo EngCulture =新的CultureInfo(EN-US,FALSE);
无效解析器()
{
如果(int.TryParse(价值,NumberStyles.Number,EngCulture,出NUM))...
}
尝试使用 CultureInfo.GetCultureInfo( EN-US)
是检索缓存,使用指定的区域性名称只读文化的一个实例。
的 http://msdn.microsoft.com/en-us/library/yck8b540.aspx
或让你的领域是只读的,所以你并不需要一个锁:
私有静态的CultureInfo _culture = CultureInfo.ReadOnly(新的CultureInfo(EN-US));
I have a multi-threaded application which parses some text and it needs to use English Culture Info for parsing numbers from this text. So, i do not want to create EngCulture everytime i call the parsing function. Currently i am passing EngCulture as a parameter but i am not happy with this. I want to define the EngCulture as a static member so it will be shared by threads.
Msdn documentation says that "Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe." I am just using the following function, so how could i know whether TryParse uses any instance members of the EngCulture or not?
public static CultureInfo EngCulture = new CultureInfo("en-US", false);
void parser()
{
if (int.TryParse(value, NumberStyles.Number, EngCulture, out num))...
}
Try to use CultureInfo.GetCultureInfo("en-US")
that "retrieves a cached, read-only instance of a culture using the specified culture name."
http://msdn.microsoft.com/en-us/library/yck8b540.aspx
or make your field to be readonly so you will not need a lock:
private static CultureInfo _culture = CultureInfo.ReadOnly(new CultureInfo("en-US"));
这篇关于CultureInfo的线程安全的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!