显然,System.Threading.Timer回调应该会延迟一点。但是,它可以提早召唤吗?
例如,如果您启动秒表并安排计时器在1000毫秒内运行回调,秒表是否可能在回调中显示999?或者我们可以依靠它必须显示1000或更多的事实?
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) { }
}
}