Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CultureInfo thread safety

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))...
}
like image 623
lockedscope Avatar asked Jul 21 '10 11:07

lockedscope


1 Answers

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"));
like image 88
abatishchev Avatar answered Sep 28 '22 03:09

abatishchev