Windows.Forms.Timer真实精度究竟是多少?并非文档所述55毫秒
Windows Forms Timer精度疑问与UI场景下的定时器选择
问题背景
我需要定期更新UI,System.Windows.Forms.Timer运行在UI线程,看起来是理想选择,但MSDN文档指出:
Windows Forms Timer组件是单线程的,**精度限制为55毫秒。**如果需要更高精度的多线程定时器,请使用System.Timers命名空间下的Timer类。
这让我以为它的间隔值只能是55的倍数,但实际测试结果并非如此:
测试代码
private Stopwatch _systemTimersTimerStopwatch = Stopwatch.StartNew(); private Stopwatch _windowsFormsTimerStopwatch = Stopwatch.StartNew(); private long _systemTimersTimerLastElapsed; private long _windowsFormsTimerLastElapsed; private void SystemTimersTimer_Elapsed(object sender, System.Timers.ElapsedEventArgs e) { //if (InvokeRequired) { BeginInvoke(new MethodInvoker(delegate { long elapsed = _systemTimersTimerStopwatch.ElapsedMilliseconds; if (_systemTimersTimerLastElapsed != 0) { Console.WriteLine($"+ System.Timers.Timer: {elapsed - _systemTimersTimerLastElapsed,2} ms"); } _systemTimersTimerLastElapsed = _systemTimersTimerStopwatch.ElapsedMilliseconds; })); //} } private void WindowsFormsTimer_Tick(object sender, EventArgs e) { long elapsed = _windowsFormsTimerStopwatch.ElapsedMilliseconds; if (_windowsFormsTimerLastElapsed != 0) { Console.WriteLine($"- Windows.Forms.Timer: {elapsed - _windowsFormsTimerLastElapsed,2} ms"); } _windowsFormsTimerLastElapsed = _windowsFormsTimerStopwatch.ElapsedMilliseconds; }
测试结果
将两个定时器的Interval属性均设为1,输出如下:
+ System.Timers.Timer: 15 ms - Windows.Forms.Timer: 15 ms + System.Timers.Timer: 16 ms - Windows.Forms.Timer: 20 ms + System.Timers.Timer: 15 ms - Windows.Forms.Timer: 10 ms + System.Timers.Timer: 16 ms - Windows.Forms.Timer: 18 ms + System.Timers.Timer: 16 ms - Windows.Forms.Timer: 14 ms
疑问点
- 显然
System.Windows.Forms.Timer的精度高于文档所述的55毫秒,这个55毫秒数值的来源是什么?另一篇MSDN文档《Limitations of the Windows Forms Timer Component's Interval Property》并未提及该55毫秒限制。 - 在我的UI更新场景下,使用
System.Timers.Timer相比System.Windows.Forms.Timer是否有优势?我认为没有,因为仍需调用BeginInvoke。
内容的提问来源于stack exchange,提问作者RadarNyan
相关产品推荐
相关产品推荐

