定时器使用

最近工作中遇到了一个场景,需要定时请求后台数据并更新到界面上,在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();
        }
    }
}
相关推荐
爱吃苹果的日记本14 小时前
数据结构第一课
c语言·数据结构·数据库·学习·c#
唐青枫15 小时前
C#.NET PInvoke 深入解析:封送、内存布局与原生互操作实战
c#·.net
软件黑马王子19 小时前
24.Editor 资源加载:主要作用和基本原理
开发语言·前端框架·c#
慧都小妮子19 小时前
用 Python 批量把 PDF 参考文献排成 MLA 格式:Spire.Doc for Python 实战
python·pdf·c#·spire.doc·mla格式·参考文献排版·pdf批量处理
FuckPatience1 天前
WPF 窗体唤醒,判断是否已存在,存在则弹出
wpf
UIU1141 天前
补码运算与整数溢出(上
学习·c#·补码·补码运算
程序员清风1 天前
从单体应用到微服务:后端系统拆分的基本方法
微服务·架构·wpf
曹牧1 天前
C#:模态对话框
开发语言·c#
咕白m6251 天前
C# 如何限制 PDF 复制、打印权限?
c#·.net
yume_sibai1 天前
正则表达式完全指南(基础语法 + 实战应用 + 性能优化 + 最佳实践)
开发语言·正则表达式·c#