【发布时间】:2012-06-08 00:26:27
【问题描述】:
我目前正在尝试编写一个每秒准确运行 100 次相同代码的应用程序。我已经使用 .NET 框架的内置计时器进行了一些测试。我测试了 System.Threading.Timer 类、System.Windows.Forms.Timer 类和 System.Timers.Timer 类。对于我正在尝试做的事情,它们似乎都不够准确。 我发现了 PerformanceCounters 并且目前正在尝试在我的应用程序中实现它。 但是,我的程序在空闲时占用了 CPU 的整个内核时遇到了一些麻烦。 我只需要它每秒激活 100 次。我的循环如下所示:
long nextTick, nextMeasure;
QueryPerformanceCounter(out start);
nextTick = start + countsPerTick;
nextMeasure = start + performanceFrequency;
long currentCount;
while (true)
{
QueryPerformanceCounter(out currentCount);
if (currentCount >= nextMeasure)
{
Debug.Print("Ticks this second: " + tickCount);
tickCount = 0;
nextMeasure += performanceFrequency;
}
if (currentCount >= nextTick)
{
Calculations();
tickCount++;
nextTick += countsPerTick;
}
}
如您所见,大多数情况下,程序将通过不断地运行 while 循环来等待再次运行 Calculations()。有没有办法阻止这种情况发生?我不想降低运行我的程序的计算机的速度。 不幸的是,System.Thread.Thread.Sleep 也很“不准确”,但如果没有其他解决方案,我可以使用它。
我基本上要问的是:有没有办法让无限循环减少 CPU 密集度?有没有其他方法可以准确地等待特定的时间?
【问题讨论】:
标签: c# multithreading winapi cpu performancecounter