SetTimeZoneInformation不会更新另一个.NET应用程序的DateTime.Now
以下是我更改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")));
这是另一个应用程序(App#2):
static void Main(string[] args) { while (true) { Console.WriteLine(DateTime.Now); Thread.Sleep(500); } }
DateTime的输出永远不会更新到新的TimeZone,为什么?
编辑
正如@Jon所说,通过添加CultureInfo.CurrentCulture.ClearCachedData();
新日期将更新。 但正如所说,我希望所有其他应用程序使用这个新的TimeZone。 我使用DateTime.Now
在后台运行了很多应用程序,在检索本地更新日期之前指定每次清除缓存都是不好的…
我怀疑你的第二个应用程序只是使用缓存的时区数据。 (这是一个单独的过程,毕竟 – 清除应用程序1中的缓存不会影响应用程序2中的任何进程内缓存。)尝试在应用程序2中调用TimeZoneInfo.ClearCachedData
,看看是否可以解决问题。