Obviously, System.Threading.Timer callback should be expected to be late a bit. However, can it be called early?
For instance, if you start a Stopwatch and schedule the timer to run the callback in 1000 ms, is it possible that the Stopwatch will be showing 999 in the callback? Or can we count on the fact that it must 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) { }
}
}