开发者

Getting localized strings from language resource files in a backgroundworker thread

I develop an application which is localized, has a multilingual interface. To do this I use winform's localazible features and also language string resources. So far so good, it works perfectly.

The problem comes, when I have to try to get a localized string inside a background worker process: it can't use the current UI culture, but default instead. ResourceManager's GetString method returns the default language string, not the string by CurrentUICulture. Note, it w开发者_Python百科orks perfectly in the main thread, the problem is inside backgroundworker.

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

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

Thanks in advance!


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


Even though the accepted answer to this question is absolutely right, I would like to complement it with something I learned after having to localize a quite large system.

Setting the Thread.CurrentCulture and Thread.CurrentUICulture every time you need to use a BackgroundWorker can be very error-prone and hard to maintain, specially if you're doing this on several different parts of the system. To avoid that, 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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜