问题
I have a situation where I need to set my process' locale to en-US.
I know how to do this for the current thread:
System.Threading.Thread.CurrentThread.CurrentCulture =
System.Globalization.CultureInfo.CreateSpecificCulture("en-US");
But my application uses BackgroundWorkers to do some processing, and the locale for these worker threads seems not to be affected by the above change to their spawning main-thread.
So how can I set the locale for all the threads in my application without setting it in each one manually?
回答1:
You'll have to change the operating system locale if you want to do that. For what reason do you want BackgroundWorkers to run in en-US?
You should have your business layer running in an invariant culture, and only have a specific culture for the end user's UI.
If you are using the BackgroundWorker component, and have to do this you could try something like this in the DoWork method:
// In DoWork
System.Globalization.CultureInfo before = System.Threading.Thread.CurrentThread.CurrentCulture;
try
{
System.Threading.Thread.CurrentThread.CurrentCulture =
new System.Globalization.CultureInfo("en-US");
// Proceed with specific code
}
finally
{
System.Threading.Thread.CurrentThread.CurrentUICulture = before;
}
回答2:
With 4.0, you will need to manage this yourself by setting the culture for each thread. But with 4.5, you can define a culture for the appdomain and that is the preferred way to handle this. The relevant apis are CultureInfo.DefaultThreadCurrentCulture and CultureInfo.DefaultThreadCurrentUICulture.
回答3:
Use this:
worker.RunWorkerAsync(Thread.CurrentThread.CurrentCulture.LCID);//Pass the LCID as argument
after on do work make this:
Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo(int.Parse(e.Argument.ToString()));
回答4:
We use helper class for BackgroudWorker like this:
public static class BackgroundWorkerHelper
{
public static void RunInBackground(Action doWorkAction, Action completedAction, CultureInfo cultureInfo)
{
var worker = new BackgroundWorker();
worker.DoWork += (_, args) =>
{
System.Threading.Thread.CurrentThread.CurrentCulture = cultureInfo;
System.Threading.Thread.CurrentThread.CurrentUICulture = cultureInfo;
doWorkAction.Invoke();
};
worker.RunWorkerCompleted += (_, args) =>
{
System.Threading.Thread.CurrentThread.CurrentCulture = cultureInfo;
System.Threading.Thread.CurrentThread.CurrentUICulture = cultureInfo;
completedAction.Invoke();
};
worker.RunWorkerAsync();
}
}
Example usage:
BackgroundWorkerHelper.RunInBackground(() => { Work(); }, () => { AfterWork(); },Thread.CurrentThread.CurrentCulture);
来源:https://stackoverflow.com/questions/1460023/how-can-i-change-the-currentculture-of-the-entire-process-not-just-current-thre