CultureInfo for any thread

Sometimes I need to set the CurrentThread Culture and the UI Culture, to avoid some problem in date or number conversion.
By default I work on the same thread, but not today.

With only this code you change the culture for the current thread

var cultureITA = CultureInfo.CreateSpecificCulture("it-IT");

Thread.CurrentThread.CurrentUICulture = cultureITA;
Thread.CurrentThread.CurrentCulture = cultureITA;

This is great if you don’t create any other thread or background worker.
That’s because any other thread will be created with the OS culture setting.
In .net 4.5 there is a solution, use CultureInfo.DefaultThread:

var cultureITA = CultureInfo.CreateSpecificCulture("it-IT");

CultureInfo.DefaultThreadCurrentCulture = cultureITA;
CultureInfo.DefaultThreadCurrentUICulture = cultureITA;

So if you want be sure to change always the current culture use this:

var cultureITA = CultureInfo.CreateSpecificCulture("it-IT");

Thread.CurrentThread.CurrentUICulture = cultureITA;
Thread.CurrentThread.CurrentCulture = cultureITA;
Application.CurrentCulture = cultureITA;

CultureInfo.DefaultThreadCurrentCulture = cultureITA;
CultureInfo.DefaultThreadCurrentUICulture = cultureITA;

source by MSDN

Annunci

Informazioni su Andrea Regoli

Project Manager .Net Developer WPF WP7 Asp.Net c# javascript ajax SQL sharepoint
Questa voce è stata pubblicata in .Net, c# e contrassegnata con , , , , . Contrassegna il permalink.

Rispondi

Inserisci i tuoi dati qui sotto o clicca su un'icona per effettuare l'accesso:

Logo WordPress.com

Stai commentando usando il tuo account WordPress.com. Chiudi sessione / Modifica )

Foto Twitter

Stai commentando usando il tuo account Twitter. Chiudi sessione / Modifica )

Foto di Facebook

Stai commentando usando il tuo account Facebook. Chiudi sessione / Modifica )

Google+ photo

Stai commentando usando il tuo account Google+. Chiudi sessione / Modifica )

Connessione a %s...