Changing an application's locale without changing the Windows locale

╄→尐↘猪︶ㄣ 提交于 2021-01-27 05:31:42

问题


I've got an interesting situation where locale settings has messed with my C# application, because I failed to realize that methods like Double.Parse will not convert "1000" to 1000, but do something unexpected due to the different numbering format.

One solution to my problem would be to use something like double d = double.parse( "1000", new CultureInfo("en-US"));. Currently, I don't pass the CultureInfo. However, instead of having to make this change throughout the code, I was wondering if it's possible to affect the locale of just my application upon startup.

I have found an article on MSDN that says I can achieve this with the following code:

using System.Threading;
using System.Globalization;
Thread.CurrentThread.CurrentCulture = new CultureInfo("en-US");
Thread.CurrentThread.CurrentUICulture = new CultureInfo("en-US");

But it doesn't say whether or not worker threads spawned from the main thread will also inherit the parent's culture.

I assume this is not the case, as in .NET 4.5 there is apparently a new CultureInfo.DefaultThreadCurrentCulture property that specifies the culture for all threads in the app domain, but there isn't anything like this in .NET 4.0.

Can anyone recommend a nice solution for this locale issue?


回答1:


If new threads don't use the same locale you can start them like this:

Thread theNewThread = new Thread(() =>
{
    Thread.CurrentThread.CurrentCulture = new CultureInfo("en-US");
    Thread.CurrentThread.CurrentUICulture = new CultureInfo("en-US");

    //Make something else
});
theNewThread.Start();

Or in other way;

public static void Start(this Thread thread, CultureInfo cu)
{
    //Set the CU here..

    thread.Start();
}

Didn't tried this but I gess it could work




回答2:


I ended up just trying it out. In .NET 4.0, new threads do not inherit the locale of the thread they are created from. I did set CurrentCulture and CurrentUICulture per the MSDN documentation and all of the tests yesterday passed, so that's a good thing.




回答3:


You would probably have to set them manually on .NET 4.0, like FelipeP suggested, since the new ones will always start with the system default culture (see details here Set default thread culture for all thread?)



来源:https://stackoverflow.com/questions/18411960/changing-an-applications-locale-without-changing-the-windows-locale

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!