我有一个函数(比如说foo()
),它会不时以可变的间隔被调用。当它被调用时,它会检查时间并相应地采取行动。
我通过以下方式做到了这一点:
对象在
Forms.Timer
需要时调用函数在函数中使用一个
Diagnostics.Stopwatch
对象来确定时间和决定做什么。
但是我有以下问题:当foo()
被定时器的回调调用时,ElapsedMilliseconds
秒表对象的值通常低于预期。例如,计时器设置为 1000,因此在foo()
调用 1000 毫秒后,但在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
返回比计时器声称的更早的值,尽管间隔结束,但不会绘制下一项