c#计时器不准确?

Rap*_*ael 2 c# timer visual-studio-2013

我有一个功能,应该在一个特定的间隔后发送一个信号,精确到1毫秒(ms).但似乎我的计时器需要的时间比他应该的长,即我将功能传递给TimeSpan 20ms,但计时器需要每个刻度30ms.我现在自己写了一个计时器,Stopwatch但我还在想为什么计时器需要更多的时间来执行?

private System.Timers.Timer timer;

private void startResetTimer(TimeSpan time)
{
    timer = new System.Timers.Timer(time.TotalMilliseconds);
    timer.Elapsed += OnTimedEvent;
    timer.AutoReset = true;
    timer.Enabled = true;
}

private void OnTimedEvent(Object source, ElapsedEventArgs e)
{
    if (!waitForTimerReset.Set())
        Console.WriteLine("Could not wake up any threads!");
}
Run Code Online (Sandbox Code Playgroud)

在我的代码中,计时器唯一执行的是waitForTimerReset.Set()允许线程在被a停止后继续运行的方法ManualResetEvent,这意味着此调用不应该花费10毫秒.

Pat*_*man 8

不.计时器根本不准确.这不是它的预期目的.至少需要设置为间隔的时间.

'问题'是:定时器运行的线程在发生滴答之后停止.然后处理器需要做一些其他工作,并在完成该工作一段时间后返回并进行下一次打勾.这就是为什么这样的计时器不准确.

要解决这个问题,您有时可以计算start和now之间的差异,并使用它而不是计算滴答.

  • _在你设置为interval_时,它将需要__at至少__这就是所有保证. (2认同)