CultureInfo.ClearCachedData不起作用。它随机有时有时不工作 [英] CultureInfo.ClearCachedData does not work. It randomly sometimes works sometimes not
问题描述
我想检测区域设置更改,并在WPF应用程序中以正确的格式显示日期。但是CultureInfo.ClearCachedData有一个奇怪的问题。它随机地不是工作。有人知道为什么,为此解决办法吗?我知道区域设置存储在注册表中,但是它是非常原始的,以破译 HKCU\Control Panel\International 的内容,并从中手动构建一个CultureInfo。
I want to detect the regional settings changes and show the dates in the correct format in a WPF application. But there is a strange problem with CultureInfo.ClearCachedData. It randomly either works either not. Does anybody know why, and a workaround for this ? I know that the regional settings are stored in the registry, but it's too primitive to decipher the content of HKCU\Control Panel\International and build a CultureInfo manually from it.
我已经把它放在一个更大的应用程序中,CultureInfo.ClearCachedData的失败率几乎是100%。
I've put this in a bigger application and the rate of CultureInfo.ClearCachedData failure is almost 100% there.
Window1.xaml .cs:
Window1.xaml.cs:
using System;
using System.Globalization;
using System.Windows;
using System.Windows.Interop;
namespace WpfApplication1
{
partial class Window1 : Window
{
int i = 0;
public Window1()
{
InitializeComponent();
ShownCurrentCulture();
Loaded += (x, y) => HwndSource.FromHwnd(
new WindowInteropHelper(this).Handle).AddHook(WndProc);
}
IntPtr WndProc(IntPtr hwnd, int msg,
IntPtr wParam, IntPtr lParam, ref bool handled)
{
if (msg == 0x1a) // WM_SETTINGCHANGE
{
// CultureInfo.CurrentCulture is sometimes changed,
// sometimes not
ShownCurrentCulture();
}
return IntPtr.Zero;
}
void ShownCurrentCulture()
{
CultureInfo.CurrentCulture.ClearCachedData();
Title = i++ + " " + CultureInfo.CurrentCulture;
}
}
}
推荐答案
经过一些更多的试验,我发现只有新创建的线程才能正确地获得更新的文化。 CultureInfo.CurrentCulture在旧线程上随机返回旧的(Thread.CurrentThread.CurrentCulture)或更新的文化。
After some more trials I found out that only the newly created threads get the updated culture correctly. CultureInfo.CurrentCulture on an old thread returns randomly either the old (Thread.CurrentThread.CurrentCulture) or the updated culture.
如果Thread.CurrentThread.CurrentCulture被修改,文化信息.CentrentCulture在调用ClearCachedData之后不会得到更新,否则将被更新。
Probably if Thread.CurrentThread.CurrentCulture was modified, CultureInfo.CurrentCulture won't get updated on that tread after a call to ClearCachedData, otherwise it gets updated.
这篇关于CultureInfo.ClearCachedData不起作用。它随机有时有时不工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!