定时器使用

最近工作中遇到了一个场景,需要定时请求后台数据并更新到界面上,在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();
        }
    }
}
相关推荐
黑咩狗夜.cm12 分钟前
(aspose.words .net)内容分别固定在一行左右俩端
c#·word·.net
刚子编程25 分钟前
C# Join 实战:左连接写法、字符串拼接与 EF Core 性能调优
开发语言·c#·solr·join
小清兔1 小时前
Addressable的设置打包流程
笔记·游戏·unity·c#
rockey6272 小时前
AScript中一个很有意思的语法
c#·.net·script·eval·expression·动态脚本
刚子编程2 小时前
C# Join 深度解析:参数顺序、多表关联与空值处理最佳实践
开发语言·c#·最佳实践·join·多表关联·空值处理
天天代码码天天2 小时前
C# OnnxRuntime 实现车牌检测识别
c#·车牌识别·号牌识别
刚子编程3 小时前
C# Join 进阶:GroupJoin、性能对决与自定义比较器
java·servlet·c#·join
海盗12344 小时前
C#中的IEqualityComparer<T>使用
开发语言·c#
IT策士7 小时前
Python Word操作:从入门到精通
python·c#·word