这是我更改 TimeZoneInfo (App #1) 的方法:
private static void ChangeTimeZone(TimeZoneInfo tzi)
{
TIME_ZONE_INFORMATION actual = new TIME_ZONE_INFORMATION();
NativeMethods.GetTimeZoneInformation(out actual);
if (tzi == null || actual.StandardName == tzi.StandardName)
return;
TIME_ZONE_INFORMATION newZone = (TIME_ZONE_INFORMATION)tzi;
RunWin32Method(() => NativeMethods.SetTimeZoneInformation(ref newZone));
// Update .NET
CultureInfo.CurrentCulture.ClearCachedData();
TimeZoneInfo.ClearCachedData();
// Notify all windows that we changed a Windows setting.
// result is True
IntPtr ptr;
System.Diagnostics.Debug.WriteLine(NativeMethods.SendMessageTimeout(NativeMethods.HWND_BROADCAST, NativeMethods.WMI_SETTING_CHANGE,
IntPtr.Zero, IntPtr.Zero, 0x00, 1000, out ptr));
}
当我调用我的方法时:
ChangeTimeZone(TimeZoneInfo.GetSystemTimeZones().First(e => !e.SupportsDaylightSavingTime));
// Stopping debugger and watching other .NET App then continue to next instruction
ChangeTimeZone(TimeZoneInfo.GetSystemTimeZones().First(e => e.StandardName.Contains("Romance")));
这是另一个应用程序(应用程序#2):
static void Main(string[] args)
{
while (true)
{
Console.WriteLine(DateTime.Now);
Thread.Sleep(500);
}
}
DateTime 的输出永远不会更新到新的 TimeZone,为什么?
编辑
正如@Jon 所说,通过添加CultureInfo.CurrentCulture.ClearCachedData();
新日期将被更新。但如前所述,我希望所有其他应用程序都使用这个新的 TimeZone。我有很多应用程序在后台运行,DateTime.Now
在检索本地更新日期之前指定每次清除缓存会很糟糕......