如何用DispatcherTimer提高运行总时间的精确度
我的背景:
有两个矩形,矩形间有一条线连接,在仿真的时候要求有一个三角箭头从线的一端移动道另一端。我给定了100ms的总时间,让箭头跳跃5次。
我用DispatcherTimer,间隔100/5 = 20ms运行一次Tick事件,经测试从开始第一次到最后一次运行结束经常性的在150ms左右。即使Tick事件中什么也不做,也需要130ms。
为解决这个问题,用了多个方案,最终下面的方案时间最短,大概在105ms左右
使用 Stopwatch 精确计时
1.让DispatcherTimer间隔时间变的很短,我这里用了1ms
DispatcherTimer _timer = new(){ Interval = TimeSpan.FromMilliseconds(1) };
2.在Tick事件中应用Stopwatch来计算需要运行的步骤
var elapsedMs = _watch.Elapsed.TotalMilliseconds;//经过的毫秒
int expectedStep = (int)(elapsedMs / interval);//当前应该在第几步
if (expectedStep > _currentStep && _currentStep < simInfo.MoveCount)
{
_currentStep = expectedStep;
// do thing
if (_currentStep >= simInfo.MoveCount)
{
_timer.Stop();
//恢复部分参数
Debug.WriteLine($“仿真用时:{_watch.ElapsedMilliseconds}”);
}
}