winforms Windows.Forms.Timer的真实的准确性是多少?(不是55 ms)

8hhllhi2  于 8个月前  发布在  Windows
关注(0)|答案(1)|浏览(75)

我试图定期更新UI,System.Windows.Forms.Timer似乎是显而易见的选择,因为它运行在UI线程上,但是在MSDN页面Timer Class上有一个注解说:
Windows窗体计时器组件是单线程的,并且**的精度限制为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的精度低于MSDN页面上提到的“55毫秒”,这个数字是从哪里来的?有另一个名为Limitations of the Windows Forms Timer Component's Interval Property的MSDN页面没有提到这个“55毫秒”限制。
另外,对于我的用例,使用System.Timers.Timer比使用System.Windows.Forms.Timer有什么优势吗?我的猜测是没有,因为我需要使用BeginInvoke无论如何。

db2dz4w8

db2dz4w81#

根据文档,.NET框架的时钟可以下降到100纳秒或千万分之一秒的“ticks”。
您可以将每个tick视为一个事件,每100纳秒可以更新一次UI。
我刚刚构建了一个在Windows窗体中使用.NET框架计时器的窗体。它每天损失8分钟。我认为他们只是意味着计时器的精度是在+\正负55毫秒每分钟?还是第二个
文件不清楚。

相关问题