1秒后首次觸發,之后每2秒觸發一次
using System.Threading;
class Program
{
static void Main()
{
var timer = new Timer(
callback: state => Console.WriteLine($"觸發時間: {DateTime.Now:T}"),
state: null,
dueTime: 1000,
period: 2000
);
Console.ReadLine();
timer.Dispose();
}
}
輕量級,基于線程池,適合高性能后臺任務。
無事件機制,通過回調函數觸發。
手動控制 啟動/停止(通過 Change 方法)。
不直接支持 UI 操作(需手動切換線程)。
二、 System.Timers.Timer
間隔1秒執行一次
using System.Timers;
class Program
{
static void Main()
{
var timer = new System.Timers.Timer(interval: 1000);
timer.Elapsed += (sender, e) => Console.WriteLine($"觸發時間: {e.SignalTime:T}");
timer.AutoReset = true;
timer.Start();
Console.ReadLine();
timer.Stop();
}
}
每天23點59分59秒執行一次任務
using System.Timers;
class DailyTask
{
static Timer timer;
static void Main()
{
SetTimer();
Console.WriteLine("定時服務已啟動...");
}
static void SetTimer()
{
var now = DateTime.Now;
var target = new DateTime(now.Year, now.Month, now.Day, 23, 59, 59);
if (now > target) target = target.AddDays(1);
timer = new Timer((target - now).TotalMilliseconds);
timer.Elapsed += (s,e) => {
Console.WriteLine($"{DateTime.Now} 執行每日任務");
timer.Interval = TimeSpan.FromDays(1).TotalMilliseconds;
};
timer.Start();
}
}
基于事件(Elapsed 事件),代碼更易讀。
支持自動重置(AutoReset 屬性控制是否循環)。
可綁定到 UI 線程(通過 SynchronizingObject,僅 WinForms)。
適合需要事件機制的場景(如 UI 定時更新)。
三、using System.Windows.Threading
using System.Windows.Threading;
public partial class MainWindow : Window {
private DispatcherTimer _timer;
public MainWindow() {
InitializeComponent();
_timer = new DispatcherTimer();
_timer.Interval = TimeSpan.FromSeconds(1);
_timer.Tick += (s, e) => lblTime.Content = DateTime.Now.ToString("HH:mm:ss");
_timer.Start();
}
}
DispatcherTimer必須在UI線程創建
默認Interval為1秒更新
MVVM模式需實現INotifyPropertyChanged接口
兩種實現方式各有適用場景,MVVM更適合復雜業務
注意避免直接在其他線程修改UI元素,這是選擇DispatcherTimer而非System.Timers.Timer的主要原因。如需動態調整間隔時間,可通過修改Interval屬性實現
四、using System.Threading.Tasks;
using System.Threading.Tasks;
public void UploadTimer()
{
Task.Run(async () =>
{
while (IsTurnOnOk)
{
try
{
Test();
await Task.Delay(5000);
}
catch (Exception ex)
{
}
}
});
}
支持 async/await 語法糖
提供任務取消(CancellationToken)
支持任務延續(ContinueWith)
并行任務處理(Task.WhenAll/WhenAny)
?與DispatcherTimer的區別?:
Tasks 是通用的異步編程模型
DispatcherTimer 專為UI線程定時器設計
Tasks 不自動關聯UI線程上下文
閱讀原文:原文鏈接
該文章在 2025/6/17 13:49:24 編輯過