views:

49

answers:

2

I'm creating a windows service that runs multiple threads. Can I set the culture of my entire appDomain, instead of setting it to each thread separately?

+2  A: 

You could have a custom method that will fire threads and set culture automatically:

static bool StartThread(WaitCallback callback, object state)
{
    return ThreadPool.QueueUserWorkItem(s =>
    {
        // Set the culture
        Thread.CurrentThread.CurrentCulture = new CultureInfo("es-ES");
        // invoke the callback
        callback(s);
    }, state);
}

And when you need to start a new thread simply use this method:

StartThread(state => { /** Do some processing on a new thread **/ }, null);
Darin Dimitrov
Nice solution... but it miss the target - I need something that will set the culture even when I forget to set it. The same can happen here if I forget to start the thread through the 'StartThread' method. I want all the threads to inherit their culture automatically
Nissim
@Darin, Exactly. Can you show me the snippet for doing this?
Nissim
+2  A: 

This is not possible. Threads get their default culture when Windows creates the thread, initialized from the system default locale as configured in Control Panel + Region and Language. The relevant Win32 API functions are Get/SetThreadLocale().

There is no mechanism in the CLR to imbue a thread with another default. A common scenario for a thread is to start life created by unmanaged code and run lots of that unmanaged code, occasionally making a callback into managed code. That managed code will run with the Thread.CurrentCulture set to the culture selected by the unmanaged code. Or the Windows default if the unmanaged code didn't call SetThreadLocale(). Having the CLR change it would cause undiagnosable failure in the unmanaged code.

Of course you can override it explicitly but that's difficult to get right. The subtle formatting errors are easy enough to see, it gets hard when you use, say, data structures that implicitly rely on the collating orders of string. A SortedList suddenly cannot find an element back in the list that is actually present. Controlling it is hard too, lots of little threadpool thread callbacks throughout the .NET framework.

Don't mess around with this to avoid falling into traps like these, either rely on the system default or apply the CultureInfo explicitly.

Hans Passant