定时器使用

最近工作中遇到了一个场景,需要定时请求后台数据并更新到界面上,在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();
        }
    }
}
相关推荐
xiaoshuaishuai82 小时前
C# AvaloniaUI 中旋转
开发语言·c#
weixin_428005302 小时前
C#调用 AI学习从0开始-第2阶段(Function Calling+工具调用智能体)-第9天实战-实现计算器工具
开发语言·学习·c#·functioncalling·ai实现计算器工具
guygg882 小时前
基于C# + Halcon的通用ROI绘制工具
stm32·单片机·c#
双河子思3 小时前
《代码整洁之道》——读书笔记(持续更新)
开发语言·c++·c#
诙_3 小时前
unity——C#
unity·c#·游戏引擎
cici158744 小时前
C# LAS 点云读取与处理工具
stm32·单片机·c#
OnlyEasyCode4 小时前
C# 发送QQ邮箱验证码or其他
开发语言·c#
123的故事5 小时前
工具分享(2)-NSmartProxy内网穿透工具。
c#·.net·nsmartproxy
SunnyDays10117 小时前
使用 C# 添加、修改和删除 Excel VBA 宏 (无需 Microsoft Office Interop)
c#·excel··vba