2

I have a function that should send a signal after an specific interval, accurate to 1 millisecond (ms). But it seems like my timer needs slightly longer than he should, i.e. I pass the function a TimeSpan with 20ms but the timer needs 30ms per tick. I wrote now a timer myself with a Stopwatch but I'm still wondering why the timer needs more time to execute ?

private System.Timers.Timer timer;

private void startResetTimer(TimeSpan time)
{
    timer = new System.Timers.Timer(time.TotalMilliseconds);
    timer.Elapsed += OnTimedEvent;
    timer.AutoReset = true;
    timer.Enabled = true;
}

private void OnTimedEvent(Object source, ElapsedEventArgs e)
{
    if (!waitForTimerReset.Set())
        Console.WriteLine("Could not wake up any threads!");
}

In my Code the only thing the timer executes is the waitForTimerReset.Set() Method which allows Threads to continue after they got stopped by a ManualResetEvent, which means that this call should not take 10 ms.

Raphael
  • 23
  • 3

1 Answers1

8

No. The timer is not accurate at all. That is not its intended purpose. It will take at least the time you set as interval.

The 'problem' is: the thread the timer runs on is parked after the tick occurred. Then the processor takes some other work to do and comes back after some time when that job is done and makes the next tick. That is why such timers are not accurate.

To solve issue with that, you can sometimes calculate the difference between start and now and use that instead of counting the ticks.

Patrick Hofman
  • 153,850
  • 22
  • 249
  • 325
  • 2
    _It will take __at least__ the time you set as interval._ That is all that's guaranteed. – TaW Apr 10 '17 at 09:49
  • Thanks for the quick answer. So that means timers just wait at least 20ms in my example, but can use more time ? I read that timers need at least 15ms per tick, is that why the timer needs 30ms instead of 20 ? – Raphael Apr 10 '17 at 10:30
  • Yes, it can be more than 20ms. The lower bound is indeed somewhere between 15 and 16 ms. – Patrick Hofman Apr 10 '17 at 10:32