定时器使用

最近工作中遇到了一个场景,需要定时请求后台数据并更新到界面上,在C#中,有三种定时器:

1.System.Timers.Timer

2.System.Threading.Timer

3.System.Windows.Threading.DispatcherTimer

1,2两种方式差不多,都是用于后台定时任务,不涉及UI更新,我就是用了第二种,然后一段时间后导致cpu占满了,后来发先如果要在定时器中更新UI必须使用第三种方式,该方式可以在UI线程上触发事件,可以直接更新UI。

cpp 复制代码
using System;
using System.Windows;
using System.Windows.Threading;

namespace DispatcherTimerExample
{
    public partial class MainWindow : Window
    {
        private DispatcherTimer timer;

        public MainWindow()
        {
            InitializeComponent();

            // 创建 DispatcherTimer 实例
            timer = new DispatcherTimer();
            
            // 设置定时器间隔为1秒
            timer.Interval = TimeSpan.FromSeconds(1);

            // 绑定 Tick 事件处理程序
            timer.Tick += Timer_Tick;
        }

        private void Timer_Tick(object sender, EventArgs e)
        {
           //更新UI
        }

        private void startButton_Click(object sender, RoutedEventArgs e)
        {
            // 启动定时器
            timer.Start();
        }

        private void stopButton_Click(object sender, RoutedEventArgs e)
        {
            // 停止定时器
            timer.Stop();
        }
    }
}
相关推荐
上海安当技术19 分钟前
C/S 桌面软件怎么接 UKey 强认证?C# SDK 与 C 动态库集成 WinForms/Qt/工控实战
c语言·qt·c#
明如正午2 小时前
【C#】跨线程更新进度条_UpdateProgress 方法解析
c#
曹牧3 小时前
C#:`JsonConvert.DeserializeObject`
windows·c#
冷咖啡离 我的笨笨4 小时前
数据去重:通过 C# 删除 Excel 中的重复行
开发语言·c#·excel
鱼听禅7 小时前
C#学习笔记-添加编译参数到程序集自动更新程序编译时间
笔记·学习·c#
不正经学生7 小时前
C语言指针进阶:const 和野指针——给指针加锁,向野指针宣战
c语言·开发语言·c++·算法·c#
czhc11400756638 小时前
# ProcessJob 构造函数 — 语法与概念
c#
用户298698530149 小时前
无需安装 Excel,也能轻松将 CSV 转为 XLS 或 XLSX
后端·c#·excel
在世修行10 小时前
从零打造 C# 工业视觉检测系统(五):相机连接、连续取流与双路实时预览
数码相机·c#·视觉检测
JckOLF04Z10 小时前
C#客户端的异步操作
开发语言·c#