C# timer getting fired before their interval time

后端 未结 4 1573
暗喜
暗喜 2020-12-20 12:42

We\'re getting following problem while using System.Threading.Timer (.NET 2.0) from a Windows service.

  1. There are around 12 different timer objects
4条回答
  •  醉酒成梦
    2020-12-20 13:16

    Great question... and here's the reason:

    "Timing" is a tricky thing when it comes to computers... you can never rely on an "interval" to be perfect. Some computers will 'tick' the timer only every 14 to 15 milliseconds, some more frequently than that, some less frequently.

    So:

    Thread.Sleep(1);
    

    Could take anywhere from 1 to 30 milliseconds to run.

    Instead, if you need a more precise timer - you have to capture the DateTime of when you begin, and then in your timers you would have to check by subtracting DateTime.Now and your original time to see if it is "time to run" your code.

    Here's some sample code of what you need to do:

    DateTime startDate = DateTime.Now;
    

    Then, start your timer with the interval set to 1 millisecond. Then, in your method:

    if (DateTime.Now.Subtract(startDate).TotalSeconds % 3 == 0)
    {
        // This code will fire every 3 seconds.
    }
    

    That code above will fire faithfully every 3 seconds. You can leave it running for 10 years, and it will still fire every 3 seconds.

提交回复
热议问题