请注意,我问的是使用System.Threading.Timer
之类的东西调用回调函数的频率超过每15毫秒一次的情况。我并不是在问如何使用诸如System.Diagnostics.Stopwatch
甚至QueryPerformanceCounter
之类的东西来精确地对一段代码进行计时。
此外,我还阅读了相关问题:
Accurate Windows timer? System.Timers.Timer() is limited to 15 msec
这两个都没有对我的问题提供有用的答案。
此外,推荐的MSDN文章,Implement a Continuously Updating, High-Resolution Time Provider for Windows,是关于时间的事情,而不是提供连续的滴答流。
话虽如此。。。
有一大堆关于.NET timer对象的坏信息。例如,System.Timers.Timer
被标榜为“为服务器应用程序优化的高性能计时器”。不知何故,System.Threading.Timer
被认为是二等公民。传统观点认为System.Threading.Timer
是Windows Timer Queue Timers的包装器,而System.Timers.Timer
则完全是另外一回事。
现实情况则大相径庭。System.Timers.Timer
只是System.Threading.Timer
的一个薄薄的组件包装器(只需使用Reflector或ILDASM来窥探System.Timers.Timer
内部,您就会看到对System.Threading.Timer
的引用),并且有一些代码将提供自动线程同步,因此您不必这么做。
事实证明,System.Threading.Timer
并不是定时器队列定时器的包装器。至少在从.NET 2.0到.NET 3.5的2.0运行时中不是这样。几分钟的共享源命令行界面显示,运行时实现了自己的计时器队列,这与计时器队列计时器类似,但从未实际调用过Win32函数。
看起来.NET 4.0运行时也实现了自己的计时器队列。我的测试程序(见下文)在.NET 4.0下提供了与在.NET 3.5下相似的结果。我已经为计时器队列计时器创建了自己的托管包装器,并证明了我可以获得1ms的分辨率(具有相当好的准确性),因此我认为我不太可能错误地读取CLI源代码。
我有两个问题:
首先,是什么导致运行时对计时器队列的实现如此缓慢?我不能获得超过15毫秒的分辨率,精度似乎在-1到+30毫秒的范围内。也就是说,如果我请求24毫秒,我会得到23到54毫秒的间隔。我想我可以花更多的时间与CLI源代码一起追查答案,但我想这里可能会有人知道。
其次,我意识到这很难回答,为什么不使用计时器队列计时器呢?我意识到Windows1.x必须在没有这些API的Win9x上运行,但它们从Windows2000开始就存在了,如果我没记错的话,这是.NET 2.0的最低要求。是否因为CLI必须在非Windows机器上运行?
我的定时器测试程序:
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Threading;
namespace TimerTest
{
class Program
{
const int TickFrequency = 5;
const int TestDuration = 15000; // 15 seconds
static void Main(string[] args)
{
// Create a list to hold the tick times
// The list is pre-allocated to prevent list resizing
// from slowing down the test.
List<double> tickTimes = new List<double>(2 * TestDuration / TickFrequency);
// Start a stopwatch so we can keep track of how long this takes.
Stopwatch Elapsed = Stopwatch.StartNew();
// Create a timer that saves the elapsed time at each tick
Timer ticker = new Timer((s) =>
{
tickTimes.Add(Elapsed.ElapsedMilliseconds);
}, null, 0, TickFrequency);
// Wait for the test to complete
Thread.Sleep(TestDuration);
// Destroy the timer and stop the stopwatch
ticker.Dispose();
Elapsed.Stop();
// Now let's analyze the results
Console.WriteLine("{0:N0} ticks in {1:N0} milliseconds", tickTimes.Count, Elapsed.ElapsedMilliseconds);
Console.WriteLine("Average tick frequency = {0:N2} ms", (double)Elapsed.ElapsedMilliseconds / tickTimes.Count);
// Compute min and max deviation from requested frequency
double minDiff = double.MaxValue;
double maxDiff = double.MinValue;
for (int i = 1; i < tickTimes.Count; ++i)
{
double diff = (tickTimes[i] - tickTimes[i - 1]) - TickFrequency;
minDiff = Math.Min(diff, minDiff);
maxDiff = Math.Max(diff, maxDiff);
}
Console.WriteLine("min diff = {0:N4} ms", minDiff);
Console.WriteLine("max diff = {0:N4} ms", maxDiff);
Console.WriteLine("Test complete. Press Enter.");
Console.ReadLine();
}
}
}
https://stackoverflow.com/questions/3744032
复制相似问题