简体   繁体   English

更改线程文化 .NET Framework 4.6 及更高版本

[英]Change thread culture .NET Framework 4.6 and later versions

I'm trying to change a new thread CultureInfo like the sample below but:我正在尝试更改一个新线程CultureInfo像下面的示例但是:

  • Attempt1: SetCulture1() is not changing my thread尝试 1: SetCulture1()没有改变我的线程
  • Attempt2: SetCulture2() I got the exception "System.InvalidOperationException: instance is read-only" (when set CurrencyDecimalSeparator) Attempt2: SetCulture2()我得到了异常“System.InvalidOperationException: instance is read-only”(当设置 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.我注意到在 .net 4.6 之前这个示例有效。 Did something changed in 4.6? 4.6 有什么变化吗?

Thank you!谢谢!

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):虽然这种奇怪的情况没有答案( Microsoft 错误报告),但我找到了在我的代码(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;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM