如何在.Net中更改整个流程(不仅仅是当前线程)的CurrentCulture?

我有一种情况需要将我的进程’locale设置为en-US。

我知道如何为当前线程执行此操作:

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

但我的应用程序使用BackgroundWorkers进行一些处理,并且这些工作线程的区域设置似乎不受上述对其产生主线程的更改的影响。

那么如何在我的应用程序中为所有线程设置区域设置而不在每个线程中手动设置?

如果要执行此操作,则必须更改操作系统区域设置。 您希望BackgroundWorkers在en-US中运行的原因是什么?

您应该让业务层在不变的文化中运行,并且只有最终用户UI的特定文化。

如果您正在使用BackgroundWorker组件,并且必须这样做,您可以在DoWork方法中尝试这样的事情:

 // 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; } 

使用4.0,您需要通过为每个线程设置文化来自行管理。 但是使用4.5,您可以为appdomain定义文化,这是处理此问题的首选方法。 相关的apis是CultureInfo.DefaultThreadCurrentCulture和CultureInfo.DefaultThreadCurrentUICulture 。

用这个:

 worker.RunWorkerAsync(Thread.CurrentThread.CurrentCulture.LCID);//Pass the LCID as argument 

做完之后做这个:

 Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo(int.Parse(e.Argument.ToString())); 

我们为BackgroudWorker使用helper类,如下所示:

 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(); } } 

用法示例:

 BackgroundWorkerHelper.RunInBackground(() => { Work(); }, () => { AfterWork(); },Thread.CurrentThread.CurrentCulture);