定时器使用

最近工作中遇到了一个场景,需要定时请求后台数据并更新到界面上,在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();
        }
    }
}
相关推荐
上位机付工6 小时前
C#与倍福TwinCAT3进行ADS通信
开发语言·c#
土了个豆子的7 小时前
02.继承MonoBehaviour的单例模式基类
开发语言·visualstudio·单例模式·c#·里氏替换原则
疯狂的维修7 小时前
c#中public类比博图
c#·自动化
土了个豆子的9 小时前
03.缓存池
开发语言·前端·缓存·visualstudio·c#
somethingGoWay15 小时前
wpf .netcore 导出docx文件
wpf·.netcore
somethingGoWay17 小时前
wpf .netcore 导出pdf文件
pdf·wpf·.netcore
xiaowu0801 天前
策略模式-不同的鸭子的案例
开发语言·c#·策略模式
VisionPowerful1 天前
九.弗洛伊德(Floyd)算法
算法·c#
ArabySide1 天前
【C#】 资源共享和实例管理:静态类,Lazy<T>单例模式,IOC容器Singleton我们该如何选
单例模式·c#·.net core
gc_22991 天前
C#测试调用OpenXml操作word文档的基本用法
c#·word·openxml