C# 调度程序计时器问题



我对 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 秒的延迟。所以,我想是我的代码的处理造成了这种延迟,但我真的需要一个没有任何偏移的固定计时器。

对不起你的眼睛!!

延迟是由运行所有 WPF 代码(如呈现和DispatcherTimer.Tick事件(的 WPF GUI 线程引起的。渲染的优先级高于具有默认优先级的DispatcherTimer。因此,当您的Tick应该运行时还需要一些渲染时,渲染将首先执行并将您的 Tick 延迟 x 毫秒。这还不错,但不幸的是,如果您保持DispatcherTimer.Interval不变,这些延迟会随着时间的推移而累积。您可以通过缩短每 x 毫秒延迟的DispatcherTimer.Interval来提高DispatcherTimer精度,如下所示:

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);

有关更详细的说明,请参阅我的文章 CodeProject:提高 WPF 调度程序计时器精度

最新更新