更改线程区域性.NET Framework 4.6和更高版本

时间:2018-06-23 22:43:32

标签: c# .net multithreading cultureinfo

我正在尝试像下面的示例一样更改新的线程CultureInfo,但是:

  • Attempt1:SetCulture1()不会更改我的线程
  • Attempt2:SetCulture2()我收到了异常“ System.InvalidOperationException:实例为只读”(设置了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);
    }
    

我注意到在.net 4.6之前,此示例有效。 4.6发生了什么变化?

谢谢!

1 个答案:

答案 0 :(得分:2)

虽然这种奇怪的情况没有答案(Microsoft bug report),但是我发现可以在代码开头(Main方法)设置DefaultThreadCurrentCulture来解决此问题:

        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;