Getting localized strings from language resource files in the background

I am developing an application that is localized, has a multilingual interface. To do this, I use the local winform capabilities, as well as language string resources. So far so good, it works great.

The problem occurs when I need to try to get a localized string inside the background workflow: it cannot use the current UI culture, but it is used by default instead. The ResourceManager GetString method returns the default language string, not the CurrentUICulture string. Please note that it works fine in the main thread, the problem is in the background.

So, how can I get my localized strings - based on the current ui culture - from language resource files in a background workflow thread?

Environment: .net4, C #, Visual Studio 2010.

Thanks in advance!

+4
source share
2 answers

You need to set the Thread.CurrentCulture and Thread.CurrentUICulture properties in the background thread so that they match those in the foreground thread. This should be done at the beginning of the code that runs in the background thread.

+4
source

Even though the accepted answer to this question is absolutely correct, I would like to supplement it with what I learned after I localized a rather large system.

Setting up Thread.CurrentCulture and Thread.CurrentUICulture every time you need to use BackgroundWorker can be very error prone and hard to maintain, especially if you do this in several different parts of the system. To avoid this, you can create a simple class that inherits from BackgroundWorker and always sets the culture before running the code:

 public class LocalizedBackgroundWorker : BackgroundWorker { private readonly CultureInfo currentCulture; public LocalizedBackgroundWorker() { currentCulture = /* Get your current culture somewhere */ } protected override void OnDoWork(DoWorkEventArgs e) { Thread.CurrentThread.CurrentCulture = currentCulture; Thread.CurrentThread.CurrentUICulture = currentCulture; base.OnDoWork(e); } } 

Now just use the LocalizedBackgroundWorker class instead of BackgroundWorker , and you're good to go.

+2
source

Source: https://habr.com/ru/post/1348167/


All Articles