定时器使用

最近工作中遇到了一个场景,需要定时请求后台数据并更新到界面上,在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();
        }
    }
}
相关推荐
游乐码44 分钟前
c#成员属性
开发语言·c#
Never_Satisfied2 小时前
在c#中,如何删除字符串中的第x个字符
开发语言·c#
闲人编程2 小时前
定时任务与周期性调度
分布式·python·wpf·调度·cron·定时人物·周期性
Never_Satisfied2 小时前
在c#中,缩放jpg文件的尺寸
算法·c#
Never_Satisfied3 小时前
在c#中,控件的事件执行耗时操作导致窗体无法及时处理绘制、鼠标点击
开发语言·c#
zls3653653 小时前
C# WPF canvas中绘制缺陷分布map并实现缩放
开发语言·c#·wpf
Never_Satisfied4 小时前
在c#中,如何在字符串的第x个字符位置插入字符
java·开发语言·c#
bugcome_com18 小时前
C# 常量详解:从基础语法到实际应用
c#
qq_1508419919 小时前
3天基于VS2026的C#编程入门及动态调用CH341DLLA64读写I2C从机
开发语言·c#
溪水西流1 天前
NodifyEditor Zoom 机制分析
开发语言·c#·avalonia