定时器使用

最近工作中遇到了一个场景,需要定时请求后台数据并更新到界面上,在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();
        }
    }
}
相关推荐
追逐时光者7 小时前
一个致力于为 C# 程序员提供更佳的编码体验和效率的 Visual Studio 扩展插件
后端·c#·visual studio
SunflowerCoder9 小时前
EF Core + PostgreSQL 配置表设计踩坑记录:从 23505 到 ChangeTracker 冲突
数据库·postgresql·c#·efcore
阿蒙Amon12 小时前
C#每日面试题-常量和只读变量的区别
java·面试·c#
我是唐青枫12 小时前
C#.NET ConcurrentBag<T> 设计原理与使用场景
c#·.net
大王小生12 小时前
C# CancellationToken
开发语言·c#·token·cancellation
listhi52012 小时前
基于C#实现屏幕放大镜功能
开发语言·c#
该用户已不存在15 小时前
不止是初始化,4个C# 构造函数解析与实例
后端·c#·.net
曹天骄16 小时前
Cloudflare KV 使用教程(基于 Wrangler 项目)
wpf
无风听海18 小时前
深入讲解 C# 中 string 如何支持 CultureInfo
开发语言·c#
wzfj1234518 小时前
FreeRTOS xTaskCreateStatic 详解
开发语言·c#