SetTimeZoneInformation does not update DateTime.Now for another .NET Application

為{幸葍}努か 提交于 2020-01-02 10:06:35

问题


Here is how I change the 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));
}

When I call my method:

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")));

Here is the other app (App #2):

static void Main(string[] args)
{
    while (true)
    {
        Console.WriteLine(DateTime.Now);
        Thread.Sleep(500);
    }
}

Output of DateTime is never updated to the new TimeZone, why?


EDIT

As @Jon said, by adding CultureInfo.CurrentCulture.ClearCachedData(); the new date will be updated. But as said, I would that ALL other application uses this new TimeZone. I have a lot apps running in background using the DateTime.Now, it would be bad to specify each time to clear the cache before retrieve the local updated date...


回答1:


I suspect your second app is just using cached time zone data. (It's in a separate process, after all - clearing the cache in app 1 isn't going to affect any in-process caches in app 2.) Try calling TimeZoneInfo.ClearCachedData in app 2 and see if that sorts out the issue.



来源:https://stackoverflow.com/questions/10137383/settimezoneinformation-does-not-update-datetime-now-for-another-net-application

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!