views:

67

answers:

3

Is it possible to change CurrentUICulture of main thread when event is raised in worker thread?

Code for ilustration:

static void Main()
{
   //do something

  Thread workerThread = new Thread(new ThreadStart(DoWork));
  workerThread.Start();

  //do something
}

void DoWork()
{
   ConnectDatabase();

   //do some work

   ChangeLanguage(lang);

}

void ChangeLanguage(string lang)
{
   //this line changes Culture only  for worker thread
   System.Threading.Thread.CurrentThread.CurrentUICulture = System.Globalization.CultureInfo.CreateSpecificCulture(lang);

}
+1  A: 

You'd need the worker thread to know about the main thread, so it could do:

mainThread.CurrentUICulture = ...;

However, that strikes me as a fairly dangerous idea... the main thread could be half way through retrieving some resources, for example.

Why not have a method which you can invoke in the main thread (e.g. using Control.Invoke if you're using Windows Forms - the context isn't clear here) which will allow the main thread to change its own culture in a controlled way, reloading resources as necessary etc.

Jon Skeet
A: 

You need to invoke cross-thread callback, if you your application is WinForms app, then you can use ISyncronizedInvoke (it is implemented by any WinForms control).

If not you can use cross-context callback:

static void Main()
{
  Thread workerThread = new Thread(new ParameterizedThreadStart(DoWork));
  workerThread.Start(Thread.CurrentContext);
}

void DoWork(object state)
{
   ConnectDatabase();

   //do some work

   ((Context)state).DoCallBack(() => Thread.CurrentThread.CurrentUICulture = ...);
}
arbiter
+1  A: 

Its WinForm client application and it has user settings stored in a database. Worker thread connects database (it takes some time). After successful connection, application should set language according to the user settings.

When your Thread is finished it could use MainForm.Invoke(helperMethod) and then the helperMethod is run on the main thread and can set the Culture safely.

A backgroundworker would make it even easier. It has a Completed event that runs on the main Thread.

Henk Holterman