前言
程序猿小张最近遇到了一个难题——他需要每天早上9点自动给老板发送工作报告,就像个数字化的公鸡打鸣一样准时。在C#的世界里,这样的定时任务该怎么实现呢?
定时器在编程中就像你的私人助理,可以帮你按时执行各种任务:数据备份、邮件发送、缓存清理...
今天,就让我们一起来探索C#中那些让你成为 "时间管理大师" 的定时器吧!
1. System.Timers.Timer
System.Timers.Timer
就像一个全能型选手,它是基于服务器的定时器,精度较高,适合需要在特定时间间隔重复执行的任务,特别要说明的是,它是线程安全的。
using System;
using System.Timers;
classProgram
{
static void Main()
{
var timer = new System.Timers.Timer(1000); // 1秒间隔
timer.Elapsed += (sender, e) =>
{
Console.WriteLine($"定时任务执行啦!时间:{e.SignalTime}");
};
timer.AutoReset = true; // 设置为重复触发
timer.Start();
Console.WriteLine("按任意键退出...");
Console.ReadKey();
timer.Stop();
}
}
2. System.Threading.Timer
System.Threading.Timer
是一个轻量级的定时器,它性能更好,没有UI组件依赖,适合后台任务,不过在使用时,一定要记得手动释放资源。
using System;
using System.Threading;
classProgram
{
static void Main()
{
// 参数:回调方法, 状态对象, 延迟时间, 间隔时间
var timer = new Timer(state =>
{
Console.WriteLine($"线程定时器触发!时间:{DateTime.Now}");
}, null, 1000, 2000); // 1秒后开始,每2秒触发
Console.WriteLine("按任意键退出...");
Console.ReadKey();
timer.Dispose(); // 记得释放资源
}
}
3. System.Windows.Forms.Timer
这是一个专为 Windows Forms 设计的定时器,事件在 UI 线程上触发,可以直接操作 UI 控件,非常适合用于更新用户界面元素,不过,它的精度较低(约55ms),不太适合高精度定时。
using System;
using System.Windows.Forms;
classProgram
{
static void Main()
{
var form = new Form();
var timer = new Timer { Interval = 1000 }; // 1秒间隔
timer.Tick += (sender, e) =>
{
Console.WriteLine($"窗体定时器触发!时间:{DateTime.Now}");
};
timer.Start();
Application.Run(form);
}
}
4. Stopwatch
Stopwatch
通常用来测量程序的执行时间,它的精度非常高,达到微秒级,所以换一个思路,也可以把它作为定时器,比如下面这个例子:
using System;
using System.Diagnostics;
using System.Threading;
classProgram
{
static void Main()
{
var stopwatch = new Stopwatch();
stopwatch.Start();
while (true)
{
if (stopwatch.ElapsedMilliseconds >= 1000)
{
Console.WriteLine($"高精度计时!时间:{DateTime.Now}");
stopwatch.Restart();
}
Thread.Sleep(10); // 降低CPU占用
}
}
}
5. Thread.Sleep 和 Task.Delay
有时候,我们只需要简单的延迟执行某些代码,这时候可以使用 Thread.Sleep(同步)或 Task.Delay(异步) 来实现,如:
using System;
using System.Threading.Tasks;
public class AsyncAwaitExample
{
public static async Task Main(string[] args)
{
Console.WriteLine("开始计时...");
await Task.Delay(5000); // 等待5秒
Console.WriteLine("5秒后...");
}
}
总结
现在你已经掌握了 C# 定时器的“十八般武艺”,是时候做个总结了!
- 简单任务:System.Threading.Timer/Task.Delay(Thread.Sleep)
- 服务器应用:System.Timers.Timer
现在,去用代码驯服时间吧!
该文章在 2025/6/2 12:49:18 编辑过