定时器使用

最近工作中遇到了一个场景,需要定时请求后台数据并更新到界面上,在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();
        }
    }
}
相关推荐
吴可可12313 小时前
C#用OpenCVSharp提取轮廓生成CAD多段线
c#
玖玥拾16 小时前
Unity 3D 笔记(十四)Unity/C# Socket 网络笔记3
服务器·网络·unity·c#
玖玥拾18 小时前
Unity 3D 笔记(十七)Unity/C# Socket 网络笔记6
服务器·网络·unity·c#
geovindu19 小时前
CSharp: Iterative Algorithms
开发语言·后端·算法·c#·.net·迭代算法
影寂ldy19 小时前
C# HttpClient 分片下载、断点续传、暂停取消(完整项目知识点)
开发语言·c#
code bean20 小时前
【C#】 主构造函数(Primary Constructors)的来龙去脉
开发语言·c#
Suxing921 小时前
C语言基础分享:“群租房”和“点名册”——联合体与枚举
c语言·算法·c#
czhc114007566321 小时前
725: [property: XmlIgnore]
c#
kingwebo'sZone21 小时前
C#事件声明办法
java·前端·c#
ye小杰榨 问鼎中原ZP1 天前
关于对 C# 中 ImplicitUsings,GlobalUsings 的讨论
服务器·开发语言·c#