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:

System.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.

System.Globalization.CultureInfo.DefaultThreadCurrentCulture = new System.Globalization.CultureInfo("en-US");
System.Globalization.CultureInfo.DefaultThreadCurrentUICulture = new System.Globalization.CultureInfo("en-US");

Have fun!

2 Comments

  • Hi. Also take a look at the suggestion provided by INT0X90

    blog.intninety.co.uk/.../setting-default-currentculture-in-all-versions-of-net

    it works pretty well framework versions prior to .net 4.5
    ---------------------
    @Morteza: Thanks, nice reference.


  • Hi, very nice.

    Congratulations.
    -----------------------------
    @Morteza: Thanks bro :)


Comments have been disabled for this content.