从后台工作线程中的语言资源文件获取本地化字符串
我开发了一个本地化的应用程序,具有多语言界面。为此,我使用 winform 的本地化功能以及语言字符串资源。到目前为止一切顺利,效果完美。
当我必须尝试在后台工作进程中获取本地化字符串时,问题就来了:它不能使用当前的 UI 区域性,而是使用默认区域性。 ResourceManager 的 GetString 方法返回默认语言字符串,而不是 CurrentUICulture 的字符串。请注意,它在主线程中运行良好,问题出在后台工作程序内部。
那么,如何从后台工作线程中的语言资源文件中获取基于当前用户界面文化的本地化字符串?
环境:.net4、c#、Visual Studio 2010。
提前致谢!
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 works 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!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您需要在后台线程上设置 Thread.CurrentCulture 和 Thread.CurrentUICulture 属性以匹配前台线程的属性。这应该在后台线程上运行的代码开始时完成。
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.
尽管这个问题的公认答案是绝对正确的,但我想用我在本地化一个相当大的系统后学到的东西来补充它。
每次需要使用
BackgroundWorker
时设置Thread.CurrentCulture
和Thread.CurrentUICulture
可能非常容易出错且难以维护,特别是如果您在系统的几个不同部分上执行此操作。为了避免这种情况,您可以创建一个继承自BackgroundWorker
的简单类,并始终在运行代码之前设置区域性:现在只需使用
LocalizedBackgroundWorker
类而不是BackgroundWorker
就可以开始了。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
andThread.CurrentUICulture
every time you need to use aBackgroundWorker
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 fromBackgroundWorker
and always sets the culture before running the code:Now just use the
LocalizedBackgroundWorker
class instead ofBackgroundWorker
and you're good to go.