首页 > 解决方案 > C# DispatcherTimer 问题

问题描述

我对 WPF 计时器有疑问。

这是我的代码:

System.Windows.Threading.DispatcherTimer dispatcherTimer = new System.Windows.Threading.DispatcherTimer();
dispatcherTimer.Tick += new EventHandler(DispatcherTimer_Tick);
dispatcherTimer.Interval = new TimeSpan(0, 0, 1);

如您所见,时间间隔为 1 分钟。但是当我启动计时器时,1 小时后我有 10 秒的延迟。所以,我猜是我的代码处理造成了这种延迟,但我真的需要一个修复计时器,没有任何转变。

对不起你的眼睛!!

标签: c#wpfdispatchertimer

解决方案


The delay is caused by the WPF GUI thread, which runs all WPF code, like rendering and the DispatcherTimer.Tick event. The rendering has a higher priority than a DispatcherTimer with default priority. So when at the time your Tick is supposed to run also some rendering is needed, the rendering gets executed first and delays your Tick by x milliseconds. This is not too bad, but unfortunately these delays can accumulate over time, if you leave the DispatcherTimer.Interval constant. You can improve the precision of the DispatcherTimer by shortening the DispatcherTimer.Interval for every x milliseconds delay like this:

const int constantInterval = 100;//milliseconds

private void Timer_Tick(object? sender, EventArgs e) {
  var now = DateTime.Now;
  var nowMilliseconds = (int)now.TimeOfDay.TotalMilliseconds;
  var timerInterval = constantInterval - 
   nowMilliseconds%constantInterval + 5;//5: sometimes the tick comes few millisecs early
  timer.Interval = TimeSpan.FromMilliseconds(timerInterval);

For a more detail explanation see my article on CodeProject: Improving the WPF DispatcherTimer Precision


推荐阅读