定时器使用

最近工作中遇到了一个场景,需要定时请求后台数据并更新到界面上,在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();
        }
    }
}
相关推荐
EIP低代码平台7 小时前
EIP 低代码平台 - 角色维护
低代码·c#·权限·工作流·netcore
心平气和量大福大12 小时前
C#-WPF-控件-TextBox 数据绑定
开发语言·c#·wpf
-银雾鸢尾-16 小时前
C#中HashTable相关方法
开发语言·c#
geovindu20 小时前
CSharp: Flyweight Pattern
开发语言·后端·c#·.net·享元模式·结构型模式
吴可可12320 小时前
C# CAD二次开发中如何退出窗口
c#
影寂ldy20 小时前
C# WinForm 三种自定义控件 + 完全自定义重绘控件知识点
开发语言·c#
ellis197020 小时前
C#异常相关关键字:Exceptions,throw,try,catch,finally
unity·c#
-银雾鸢尾-20 小时前
C#中的Dictionary相关方法
开发语言·c#
listening77720 小时前
HarmonyOS 6.1 全场景协同实战:从“单机”到“超级终端”的分布式重构
wpf
lzhdim21 小时前
C# 中读取CPU、硬盘和内存温度
开发语言·c#