定时器使用

最近工作中遇到了一个场景,需要定时请求后台数据并更新到界面上,在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();
        }
    }
}
相关推荐
三千道应用题2 小时前
WPF学习笔记(13)列表框控件ListBox与数据模板
wpf
阿蒙Amon9 天前
《C#图解教程 第5版》深度推荐
开发语言·c#
暖馒9 天前
C#委托与事件的区别
开发语言·c#
JosieBook9 天前
【C#】C#异步编程:异步延时 vs 阻塞延时深度对比
c#·多线程·异步·阻塞
甄天9 天前
WPF中MVVM和MVVMLight模式
c#·wpf·visual studio
冰茶_9 天前
ASP.NET Core API文档与测试实战指南
后端·学习·http·ui·c#·asp.net
_oP_i9 天前
实现 “WebView2 获取word选中内容
开发语言·c#·word
Kookoos10 天前
ABP vNext + Azure Application Insights:APM 监控与性能诊断最佳实践
后端·c#·.net·abp vnext
专注VB编程开发20年10 天前
asp.net core Razor动态语言编程代替asp.net .aspx更高级吗?
开发语言·后端·c#·asp.net·.net
安木夕10 天前
C#.Net筑基-优雅LINQ的查询艺术
c#·.net