C# event to detect Daylight Saving or even manual time change

后端 未结 3 1988
广开言路
广开言路 2020-12-07 03:45

I run an application as a service on a server and then I have multiple clients connect to that service. I display the exact server time on each of the client Window form ap

相关标签:
3条回答
  • 2020-12-07 04:29

    Well I would strongly suggest not relying on the local time to start with. Use the UTC time of the server, and then if you need to convert that to the local time you can do that wherever you want to, if you know its time zone.

    Detecting a manual time change without a useful event is slightly tougher, but could you just run a timer which executes every (say) 30 seconds and checks whether the UTC time isn't "UTC time at least timer tick + 30 seconds" with some amount of tolerance?

    You don't need to run it terribly often, so it's not like it's going to be a huge waste of resources. You could always hide this behind an API which can be replaced with a more efficient one if you ever do find a better answer :)

    0 讨论(0)
  • 2020-12-07 04:37

    Perhaps less than ideal, you could have an agent running in the foreground that listens for the TimeChanged event and forwards this to your service.

    0 讨论(0)
  • 2020-12-07 04:40

    Thank you all for your inputs, they certainly pointed me in the right direction. I was able to solve my issue and I figure to put them here for anyone down the road that find them helpful.

    So in my main program where I run the service, it has to be a sub class of ServiceBase.

    In my main function I spawned a separate thread as follow:

    new Thread(RunMessagePump).Start();
    
    private void RunMessagePump()
    {
      Application.Run(new HiddenForm())
    }
    

    This Hidden form is exactly what its name say, it is a simple form that is remain hidden by the code this.ResumeLayout(false) under its Intiailaizecomponent() code.

    Within this form's FormLoad event you can declare any System event. In my case I have

    private void HiddenForm_Load(object sender,EventArgs e)
    {
      SystemEvents.timeChanged += new EventHandler(SystemEvents_TimeChanged);
    }
    

    Voila, this works out beautifully, and I think I will use this form load event to capture any SystemEvents I want to use down the road.

    Cheers.

    0 讨论(0)
提交回复
热议问题