DispatcherTimer定时器,可以说是专门为WPF界面设计的定时器。因为这个定时器是和UI都在同一线程上的。
添加命名空间引用
cs
using System.Windows.Threading;
实例化
cs
DispatcherTimer _timer = new DispatcherTimer();
设定定时器参数
cs
/*设置定时时间方法一*/
_timer.Interval = new TimeSpan(0,1,0);//设置时间间隔h,m,s
/*设置定时时间方法二*/
timer.Interval = TimeSpan.FromMilliseconds(100);//设置的间隔为100ms
_timer.Tick += Timer_Tick;//绑定计时事件(Tick事件在UI线程执行)
_timer.DispatcherPriority = DispatcherPriority.Normal;//可选:设置定时器优先级(默认Normal)
启动、停止、修改定时时间
cs
// 重启定时器
_timer.Start();
// 暂停定时器
_timer.Stop();
// 修改时间间隔(需先停止再修改,或直接修改后生效)
_timer.Interval = TimeSpan.FromMilliseconds(500); // 改为500ms触发一次
Tick 事件处理(更新 UI)
cs
private void Timer_Tick(object sender, EventArgs e)
{
_count++;
// 直接更新UI控件(安全,因为在UI线程)
lblTimer.Content = $"计时:{_count}秒";
// 示例:计时到10秒停止
if (_count >= 10)
{
_timer.Stop();
lblTimer.Content = "计时结束!";
}
}
实例
cs
using System.Windows;
using System.Windows.Threading;
public partial class MainWindow : Window
{
private DispatcherTimer _timer;
private int _count = 0;
public MainWindow()
{
InitializeComponent();
// 1. 创建DispatcherTimer实例
_timer = new DispatcherTimer();
// 2. 设置时间间隔(单位:毫秒)
_timer.Interval = TimeSpan.FromSeconds(1); // 每秒触发一次
// 3. 绑定计时事件(Tick事件在UI线程执行)
_timer.Tick += Timer_Tick;
// 4. 可选:设置定时器优先级(默认Normal)
_timer.DispatcherPriority = DispatcherPriority.Normal;
// 5. 启动定时器
_timer.Start();
}
}
Tick 事件处理(更新 UI)
cs
private void Timer_Tick(object sender, EventArgs e)
{
_count++;
// 直接更新UI控件(安全,因为在UI线程)
lblTimer.Content = $"计时:{_count}秒";
// 示例:计时到10秒停止
if (_count >= 10)
{
_timer.Stop();
lblTimer.Content = "计时结束!";
}
}
label显示定时数据
<!-- 用于数字自增显示 -->
<Label x:Name="counterLabel"
Content="0"
HorizontalAlignment="Left"
VerticalAlignment="Top"
Margin="20,20,0,0"
FontSize="20"
Padding="6"/>
private void timer_Tick(object? sender, EventArgs e)
{
// 每次 Tick 自增并显示计数
cnt++;
Debug.WriteLine($"[{DateTime.Now:HH:mm:ss}] DispatcherTimer Tick 触发。cnt={cnt}");
// DispatcherTimer 在 UI 线程运行,可以直接更新控件;使用 null-条件以防控件未命名或未初始化
counterLabel?.SetValue(ContentControl.ContentProperty, cnt);
}