前言
程序猿小張最近遇到了一個難題——他需要每天早上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 編輯過