Reputation: 641
I'm trying to change a new thread CultureInfo
like the sample below but:
SetCulture1()
is not changing my threadAttempt2: SetCulture2()
I got the exception "System.InvalidOperationException: instance is read-only" (when set CurrencyDecimalSeparator)
static void Main(string[] args)
{
Thread th = new Thread(thread_test);
// nothing happens
SetCulture1(th);
// exception System.InvalidOperationException: instance is read-only
SetCulture2(th);
th.Start();
}
public static void SetCulture1(System.Threading.Thread thread)
{
var ci = new System.Globalization.CultureInfo("pt-BR");
ci.NumberFormat.CurrencyDecimalSeparator = ".";
thread.CurrentCulture = ci; // <-- after this culture info not change
if (thread.CurrentCulture.NumberFormat.CurrencyDecimalSeparator != ".")
{
Console.WriteLine("Nothing happened");
Console.ReadKey();
}
}
public static void SetCulture2(System.Threading.Thread thread)
{
thread.CurrentCulture = new System.Globalization.CultureInfo("pt-BR");
thread.CurrentCulture.NumberFormat.CurrencyDecimalSeparator = "."; // <-- exception throws here
}
static void thread_test()
{
Console.WriteLine("Culture: {0}", CultureInfo.CurrentCulture.DisplayName);
}
I notice that before .net 4.6 this sample works. Did something changed in 4.6?
Thank you!
Upvotes: 0
Views: 2100
Reputation: 641
While this odd situation has no answer (Microsoft bug report), I found a work around setting DefaultThreadCurrentCulture at the start of my code (Main method):
var ci = new System.Globalization.CultureInfo(System.Globalization.CultureInfo.CurrentCulture.LCID);
ci.NumberFormat.CurrencyDecimalSeparator = ".";
ci.NumberFormat.CurrencyGroupSeparator = ",";
ci.NumberFormat.NumberDecimalSeparator = ".";
ci.NumberFormat.NumberGroupSeparator = ",";
ci.NumberFormat.PercentDecimalSeparator = ".";
ci.NumberFormat.PercentGroupSeparator = ",";
System.Globalization.CultureInfo.DefaultThreadCurrentCulture = ci;
System.Globalization.CultureInfo.DefaultThreadCurrentUICulture = ci;
Upvotes: 4