当前位置: 首页 > news >正文

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

http://www.lryc.cn/news/179708.html

相关文章:

  • 【智能家居项目】裸机版本——项目介绍 | 输入子系统(按键) | 单元测试
  • 算法练习8——有序三元组中的最大值
  • git创建
  • yolov8 opencv模型部署(python版)
  • Simulink仿真封装中的参数个对话框设置
  • 【C++】class的设计与使用(十)重载iostream运算符
  • Java使用Scanner类实现用户输入与交互
  • FFmpeg 命令:从入门到精通 | ffppeg 命令参数说明
  • Chrome(谷歌浏览器)如何关闭搜索栏历史记录
  • 基于Java的宠物医院管理系统设计与实现(源码+lw+部署文档+讲解等)
  • 使用WPS自动化转换办公文档: 将Word, PowerPoint和Excel文件转换为PDF
  • 对pyside6中的textedit进行自定义,实现按回车可以触发事件。
  • Spark SQL
  • 初识多线程
  • Linux用户、用户组和文件权限的管理与实践
  • 【CMU15-445 Part-14】Query Planning Optimization I
  • 七、垃圾收集中级
  • el-menu 导航栏学习(1)
  • Axios请求封装
  • Pikachu靶场——XXE 漏洞
  • vscode登录租的新服务器
  • Verilog参数定义与仿真模块中的参数修改
  • Android studio升级Giraffe | 2022.3.1 Patch 1踩坑
  • 使用U3D、pico开发VR(二)——添加手柄摇杆控制移动
  • 【FPGA项目】图像采集及显示(2)详细设计方案
  • 查找排序部分习题 242. 有效的字母异位词 74. 搜索二维矩阵 1. 两数之和 167.两数之和 II
  • MATLAB算法实战应用案例精讲-【优化算法】冠状病毒优化算法(COVIDOA)(附MATLAB代码实现)
  • React查询、搜索类功能的实现
  • k8s搭建EFK日志系统
  • LuatOS-SOC接口文档(air780E)-- fonts - 字体库