我有一个函数(比如 foo()
),它会不时以可变间隔调用。当它被调用时,它会检查时间并采取相应的行动。
我是通过以下方式完成的:
Forms.Timer
对象在需要时调用函数Diagnostics.Stopwatch
对象在函数中用于确定时间和决定做什么。
但是我有以下问题:当 foo()
被 Timer 的回调调用时,秒表对象的 ElapsedMilliseconds
值通常低于预期。例如,计时器设置为 1000,因此在 1000 毫秒后调用 foo()
,但在 foo()
主体 ElapsedMilliseconds
内返回 900 因此 foo
表现得好像耗时是 900(尽管它应该采取操作 A,因为实际经过了 1000 毫秒,但它没有)
在 ElapsedMilliseconds 与计时器具有一致值的情况下,如何同步计时器和秒表?
编辑:一些代码
一些示例代码来解释我的问题:
//foo is the function that is called by timer's callback
public void foo()
{
//Let's see what time it is:
long currentTime = stopwatch.ElapsedMilliseconds();
Item = getCurrentItem(currentTime);
Item.Draw();
}
//this is the callback of timer
private void timer1_Tick(object sender, EventArgs e)
{
//set the timer for next time
timer1.Interval = Intervals[periodIdx++];
foo();
}
这应该在每次间隔完成时绘制其他内容,但是由于 ElapsedMilliseconds
返回的值早于计时器声明的值,因此尽管间隔结束,但不会绘制下一个项目
最佳答案
你会得到很大的不同,因为你在 1/64 秒间隔内的某个地方启动计时器。你会得到更好的结果:
private void StartTimers() {
int tick = Environment.TickCount;
while (Environment.TickCount == tick) Thread.Sleep(0);
timer1.Enabled = true;
stopwatch.Start();
}
while() 循环提高了计时器在 1/64 计时器滴答开始时启动的几率。只是改进,没有保证。而且您无法对延迟触发的 Tick 事件做任何事情,这完全取决于您的 UI 线程的响应能力。然而总是迟到。不要使用此代码,编写您的代码,以便您不关心这些计时器不同步。您可能必须减少计时器的间隔才能完成此操作,问题尚不清楚。
关于c# - 同步 Forms.Timer 和 Diagnostics.Stopwatch,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8822267/