定时器使用

最近工作中遇到了一个场景,需要定时请求后台数据并更新到界面上,在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();
        }
    }
}
相关推荐
吃一碗粉只付一碗钱11 小时前
10-令牌里的用户主键不要明文
服务器·数据库·sql·sqlserver·c#
胖纸不争14 小时前
EnergyStarZ:让 Windows 后台进程给前台让路的能效管理器(v1.2 发布)
windows·性能优化·c#·win32·ef core
影寂ldy15 小时前
WPF导航窗体+Page页面跳转 知识点整理
wpf
曹牧15 小时前
C#:The operation has timed out
开发语言·c#
He BianGu15 小时前
【WPF-Control教程】IOC 依赖注入
c#·wpf·wpf-control
He BianGu16 小时前
【WPF-Control教程】H.Extensions.Behvaiors 开发文档
c#·wpf·wpf-control
He BianGu16 小时前
【WPF-Control教程】H.Style 开发文档
c#·wpf·wpf-control
麻瓜code16 小时前
分布式锁演进:从一个用户下两单,到 Redisson,我改了四版
分布式·wpf
He BianGu17 小时前
【WPF-Control教程】MVVM 二次开发文档
c#·wpf·wpf-control
He BianGu17 小时前
【WPF-Control教程】Theme 主题系统二次开发文档
c#·wpf·wpf-control