Can the Timer be early?

Obviously, you should expect the System.Threading.Timer callback to be a little late. However, can it be called earlier?

For example, if you start a stopwatch and schedule a timer to trigger a 1000ms callback, is it possible for the stopwatch to show 999 in the callback? Or can we count on it to show 1000 or more?

public sealed class EarlyTiming : IDisposable
{
    public EarlyTiming()
    {
        stopwatch = new Stopwatch();
        stopwatch.Start();

        timer = new Timer(TimerCallback, null, 1000, Timeout.Infinite);
    }

    public void Dispose()
    {
        timer.Dispose();
    }

    private readonly Timer timer;
    private readonly Stopwatch stopwatch;

    private void TimerCallback(object state)
    {
        var elapsedMs = stopwatch.ElapsedMilliseconds;

        if (elapsedMs < 1000)
            Console.WriteLine("It was early! (" + elapsedMs + " ms)");

        try
        {
            stopwatch.Restart();
            timer.Change(1000, Timeout.Infinite);
        }
        catch (ObjectDisposedException) { }
    }
}

      

+3


source to share





All Articles