C# CultureInfo.ClearCachedData不工作。它有时起作用,有时不起作用

C# CultureInfo.ClearCachedData不工作。它有时起作用,有时不起作用,c#,wpf,datetime,localization,C#,Wpf,Datetime,Localization,我想检测区域设置的变化,并在WPF应用程序中以正确的格式显示日期。但是CultureInfo.ClearCachedData有一个奇怪的问题。它要么随机工作要么不工作。有人知道原因吗?还有解决办法吗?我知道区域设置存储在注册表中,但它太原始,无法破译HKCU\Control Panel\International的内容并从中手动构建CultureInfo 我把它放在一个更大的应用程序中,CultureInfo.ClearCachedData的失败率几乎是100% Window1.xaml.cs:

我想检测区域设置的变化,并在WPF应用程序中以正确的格式显示日期。但是CultureInfo.ClearCachedData有一个奇怪的问题。它要么随机工作要么不工作。有人知道原因吗?还有解决办法吗?我知道区域设置存储在注册表中,但它太原始,无法破译HKCU\Control Panel\International的内容并从中手动构建CultureInfo

我把它放在一个更大的应用程序中,CultureInfo.ClearCachedData的失败率几乎是100%

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)或更新的区域性


可能如果修改了Thread.CurrentThread.CurrentCulture,CultureInfo.CurrentCulture在调用ClearCachedData后不会在该踏板上更新,否则它会更新。

实际上,中提到了这一点(可能是更新的条目,因为您的答案是从'09'开始的)