我需要一个每 25 毫秒触发一次的计时器。我一直在比较默认值Timer
在 dotnet core 运行时和最新的 mono 运行时上,在 Windows 10 和 Linux(Ubuntu Server 16.10 和 12.04)之间实现。
计时器精度存在一些差异,我不太明白。
我正在使用以下代码来测试计时器:
// inside Main()
var s = new Stopwatch();
var offsets = new List<long>();
const int interval = 25;
using (var t = new Timer((obj) =>
{
offsets.Add(s.ElapsedMilliseconds);
s.Restart();
}, null, 0, interval))
{
s.Start();
Thread.Sleep(5000);
}
foreach(var n in offsets)
{
Console.WriteLine(n);
}
Console.WriteLine(offsets.Average(n => Math.Abs(interval - n)));
在 Windows 上,它无处不在:
...
36
25
36
26
36
5,8875 # <-- average timing error
在 linux 上使用 dotnet core,情况就不那么乱了:
...
25
30
27
28
27
2.59776536312849 # <-- average timing error
但单声道Timer
非常精确:
...
25
25
24
25
25
25
0.33 # <-- average timing error
Edit:即使在 Windows 上,mono 仍然保持其计时精度:
...
25
25
25
25
25
25
25
24
0.31
是什么造成了这种差异?与 mono 相比,dotnet core 运行时的处理方式是否有好处,可以证明损失的精度是合理的?