我对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秒钟的延迟。所以,我想这是我的代码的处理造成这个延迟,但我真的需要一个修复定时器,没有任何移位。
对不起你的眼睛!!
发布于 2022-02-28 10:59:57
延迟是由WPF线程造成的,该线程运行所有WPF代码,比如呈现和DispatcherTimer.Tick事件。呈现比具有默认优先级的DispatcherTimer具有更高的优先级。因此,当您的Tick在运行时也需要一些呈现时,呈现将首先执行,并将您的滴答延迟x毫秒。这还不算太糟,但不幸的是,如果您离开DispatcherTimer.Interval常量,这些延迟会随着时间的推移而累积。您可以提高DispatcherTimer的精度,方法是缩短每隔x毫秒的DispatcherTimer.Interval时间,如下所示:
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 DispatcherTimer精度上的文章
https://stackoverflow.com/questions/50794629
复制相似问题