问题描述
在 .Net 4.0 WPF 项目中,我们需要在每个线程上保持与主线程相同的 CurrentCulture.
In a .Net 4.0 WPF project, we need to keep the same CurrentCulture on each thread then we have on the main thread.
鉴于,我们可以使用如下代码初始化一个新线程的文化:
Given, we can initialize a new thread's culture with code like the following:
将信息保存在变量(上下文)中
Keep the information in a variable (context)
context.CurrentCulture = Thread.CurrentThread.CurrentCulture;
context.CurrentUICulture = Thread.CurrentThread.CurrentUICulture;
在新线程上,从保存的上下文中初始化
On the new thread, initialize from the saved context
Thread.CurrentThread.CurrentCulture = context.CurrentCulture;
Thread.CurrentThread.CurrentUICulture = context.CurrentUICulture;
但在这个 TPL、异步编程和 lambda 委托的时代,感觉不太对.
But in this age of TPL, async programming and lambda delegates, it does not feel right.
是的,我们实际上可以在应用程序运行时改变文化,但那是另外一回事了.
And yes, we actually can change the culture while the application is running, but that is another story.
您是否知道我们应该初始化以进行跟踪的任何设置、属性或配置?
Do you know of any setting, property or config we should initialize to keep track?
推荐答案
没有什么好办法,不惜一切代价避免这种情况.根本问题是文化不是 Thread.ExecutionContext 的一部分,它不会从一个线程流到另一个线程.这是一个无法解决的问题,文化是本机 Windows 线程的属性.它将始终初始化为在控制面板的区域和语言小程序中选择的系统文化.
There is no good way, avoid this at all cost. The fundamental problem is that culture is not part of the Thread.ExecutionContext, it doesn't flow from one thread to another. This is a unsolvable problem, culture is a property of a native Windows thread. It will always be initialized to the system culture as selected in Control Panel's Region and Language applet.
对文化进行临时线程本地更改很好,尝试将过程"切换到另一种文化是您将要寻找数月的错误的来源.字符串整理顺序是最令人讨厌的问题根源.
Making temporary thread-local changes to the culture is fine, trying to switch 'the process' to another culture is a source of bugs you'll be hunting for months. The string collation order is the nastiest source of problems.
此问题已在 .NET 4.5 中通过 CultureInfo.DefaultThreadCurrentCulture 和 DefaultThreadCurrentUICulture 属性修复.
this problem was fixed in .NET 4.5 with the CultureInfo.DefaultThreadCurrentCulture and DefaultThreadCurrentUICulture properties.
并在 .NET 4.6 中获得了真正的解决方案,文化现在从一个线程流向另一个线程.有关详细信息,请查看有关 CultureInfo.CurrentCulture 的 MSDN 文章.请注意,描述与行为不完全匹配,需要进行测试.
and got the real solution in .NET 4.6, culture now flows from one thread to another. Check the MSDN article for CultureInfo.CurrentCulture for details. Beware that the description does not quite match behavior, testing required.
这篇关于在 .Net 中:将 CurrentCulture 保持在新线程上的最佳方式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!