c# winform程序,DispatcherTimer被调用延迟,响应间隔长

c# winform程序,DispatcherTimer被调用延迟,响应间隔长

最近修改的问题,winform界面上两个控件的数据刷新,用DispatcherTimer定时刷新,但是在某些机器上的实际刷新时间间隔远远大于设置时间。

既然MSDN已经说了,不保证计时器在时间间隔发生时准确执行。
Timers are not guaranteed to execute exactly when the time interval occurs, but they are guaranteed to not execute before the time interval occurs. This is because DispatcherTimer operations are placed on the Dispatcher queue like other operations. When the DispatcherTimer operation executes is dependent on the other jobs in the queue and their priorities.

两个控件的计时器在程序不同层级,分别用了不同的解决方法。

修改DispatcherTimer优先级

最简单的方法,在生成计时器对象时,加一个优先级参数。
private DispatcherTimer _timer = new DispatcherTimer(DispatcherPriority.Send);

用线程计时器

这个计时器设置优先级也还是有延迟,所以采用threading timer,单独在一个线程里做数据刷新,保证了时间上及时调用。避免DispatcherTimer等在UI线程里延迟的问题。
private System.Threading.Timer _timer;

_timer = new System.Threading.Timer(new TimerCallback(OnTimerTicked));

启动计时器,参数一指定调用之前的延迟时间,参数二指定计时器时间间隔
_timer.Change(0, 100);

private void OnSysTimeUpdatingTimerTicked(object state)
{
# 注意这里的写法。因为timer线程与UI不在同一个线程,timer线程不能直接调UI控件设置变量值。
mylabel.Invoke(new Action(() => { mylabel.Text = xxxxx; }));
}

如果需要关闭计时器,设置第一个参数为-1
_sysTimeUpdatingTimer.Change(-1,100);

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值