作用
在指定时间间隔出发事件。一般用于更新UI、执行后台任务。
重要属性
- Interval:间隔,单位毫秒
- Enabled:是否启动定时器
事件
Tick:每隔Interval时间触发一次
特点
- 事件在UI线程执行,可直接更新页面控件。
- 精度低,处理耗时任务会影响下次触发
- 简单易用
示例
private void Form1_Load(object sender, EventArgs e)
{timer1.Interval = 1000;timer1.Start();
}
private void timer1_Tick(object sender, EventArgs e)
{label1.Text = DateTime.Now.ToString("HH:mm:ss");
}
系统定时器
- 命名空间:
System.Timers
- 基于线程池
- 精度较高
- 适合后台任务
- 支持自动重置
AutoReset
System.Timers.Timer timer = new System.Timers.Timer(1000);
timer.Elapsed += (sender, e) =>
{this.Invoke((Action)(() => {label1.Text = DateTime.Now.ToString("HH:mm:ss");}));
};
timer.Start();
线程定时器
- 命名空间:
System.Threading
- 基于线程池
- 轻量级,无事件,直接通过回调执行
- 灵活控制,可手动停止或释放
- 适合高性能场景,但需注意线程安全
System.Threading.Timer timer = new System.Threading.Timer(state =>
{this.Invoke((Action)(() => {label1.Text = DateTime.Now.ToString("HH:mm:ss");}));
}, null, 0, 1000); // 立即启动,间隔 1 秒
对比
特性 | Forms.Timer | Timers.Timer | Threading.Timer |
---|---|---|---|
线程模型 | UI线程 | 线程池 | 线程池 |
事件/回调 | Tick | Elapsed | 回调函数 |
UI更新 | 直接更新 | Invoke | Invoke |
精度 | 低 | 较高 | 高 |
适用场景 | UI动画、倒计时 | 后台任务、周期性处理 | 高性能后台任务 |