.NET4.5可以给所有线程设置默认的Culture了_.NET_编程开发_程序员俱乐部

中国优秀的程序员网站程序员频道CXYCLUB技术地图
热搜:
更多>>
 
您所在的位置: 程序员俱乐部 > 编程开发 > .NET > .NET4.5可以给所有线程设置默认的Culture了

.NET4.5可以给所有线程设置默认的Culture了

 2014/4/17 13:17:36  孑孓子  博客园  我要评论(0)
  • 摘要:HowtosetCurrentCultureforallthreadsinadomainin.NET4.5Before.NET4.5ifwewantedtosetCurrentCultureforthecurrentthread,wewouldneedtosetthecultureinsomewherelikeapplicationbootstrap.Forexampleinthefollowingcodewesettheculturetoen-us:线程默认的是用服务器的Cultrue
  • 标签:.net net 线程

class="pageTitle">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!

上一篇: Rails事物Transaction 下一篇: 没有下一篇了!
发表评论
用户名: 匿名