How to set CurrentCulture for all threads in a domain in .NET 4.5

Before .NET 4.5 if we wanted to set CurrentCulture for the current thread, we would need to set the culture in somewhere like application bootstrap.

For example in the following code we set the culture to en-us:

线程默认的是用服务器的 Cultrue

.NET4.5之前,只能用以下代码只能针对单个线程,如果每次执行线程 都要重新设置一下。。。

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

For single threaded application and for regular usages, the preceding code works fine and there is nothing to be worry about. But problems come to the surface if we are working on a multi-threaded application which needs to have more than one thread.

Basically in .NET platform thread culture is read from Windows system culture by default and if the system culture is different from application culture, you need to somehow set the thread's culture manually for every threads.

The same problem is even there for Tasks in Task Parallel Library which means task's operations are done in the context of the Windows system thread by default. So we need to set the current culture manually inside of each task if we are doing something relevant to localization and so on.

Fortunately in .NET 4.5 a couple of cool properties have been added to the CultureInfo class called DefaultThreadCurrentCulture and DefaultThreadCurrentUICulture. A default culture will be set to the whole domain and for all threads by assigning a culture to these properties in application bootstrap.

.NET4.5就简单了,在网站启动的时候 ,设置一下这个,所有线程 都会用这个默认的Culture了!


System.Globalization.CultureInfo.DefaultThreadCurrentCulture = new System.Globalization.CultureInfo("en-US");
System.Globalization.CultureInfo.DefaultThreadCurrentUICulture = new System.Globalization.CultureInfo("en-US");
[assembly: System.Web.PreApplicationStartMethod(typeof(Web.AppStart), "Main")]
namespace Web
{
public class AppStart
{
public static void Main()
{
//set default culture here }
}
}

Have fun!

最新文章

  1. RDCMan
  2. JS,复习
  3. [转载]python脚本删除一定时间以外的文件
  4. c++ 调用dll
  5. ubuntu 中增加鼠标右键菜单,为Windows 的exe 程序快速增加桌面快捷键
  6. WordPress BulletProof Security插件多个HTML注入漏洞
  7. 【转】树莓派学习笔记——I2C Tools 学习笔记
  8. SoupUI接口测试学习分享
  9. HTML——window.document对象练习题
  10. [Python数据挖掘]第2章、Python数据分析简介
  11. nginx学习笔记(三)
  12. POJ 2455 Secret Milking Machine 【二分】+【最大流】
  13. Source Insight 4.0常用设置
  14. Python标准库--UUID
  15. CodeForces 493B Vasya and Wrestling 【模拟】
  16. IDA IDC Tutorials: Additional Auto-Commenting
  17. 自己定义iOS上双击Home键图切换
  18. ubuntu环境下配置jdk
  19. [转]SSIS包的调用方式
  20. 蓝桥杯 算法训练 ALGO-126 水仙花

热门文章

  1. 下一个系列学习列表Spring.net+NHibernate+MVC
  2. css笔记 css用法:
  3. AlloyTouch实现下拉刷新
  4. 标准库 - unicode/utf8/utf8.go 解读
  5. U-BOOT配置过程
  6. View Controller 视图管理总结
  7. 【Mood-4】心静是一门艺术
  8. android开发之路12(android四大组件&Fragment&AsyncTask类)
  9. Oracle基础(八) 数据完整性
  10. vb.net机房收费系统之配置文件