【发布时间】:2012-01-11 15:50:24
【问题描述】:
我有一个函数(比如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 返回的值比计时器声称的更早,虽然间隔结束,但不会绘制下一项
【问题讨论】:
-
没有办法同步。
-
你想完成什么?准确的时间?使用
Windows.Forms.Timer很难做到这一点。
标签: c# .net timer synchronization stopwatch