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
c # .net timer


source to share


No one has answered this question yet

See similar questions:

24
How accurate is System.Diagnostics.Stopwatch?

or similar:

890
How can I get the app path in a .NET console app?
867
How can I generate random alphanumeric strings?
677
How to get the version of an assembly file
316
How can I convert String to Int?
311
Android timer? How?
134
WPF Timer Like C # Timer
32
Replace timer in android
7
When my timer is ticking ..... NET Memory Leak
0
C # IDisposable correct use and call
-1
The specified value is not returned



All Articles
Loading...
X
Show
Funny
Dev
Pics