1秒后首次觸發(fā),之后每2秒觸發(fā)一次
using System.Threading;
class Program
{
static void Main()
{
var timer = new Timer(
callback: state => Console.WriteLine($"觸發(fā)時(shí)間: {DateTime.Now:T}"),
state: null,
dueTime: 1000,
period: 2000
);
Console.ReadLine();
timer.Dispose();
}
}
輕量級(jí),基于線(xiàn)程池,適合高性能后臺(tái)任務(wù)。
無(wú)事件機(jī)制,通過(guò)回調(diào)函數(shù)觸發(fā)。
手動(dòng)控制 啟動(dòng)/停止(通過(guò) Change 方法)。
不直接支持 UI 操作(需手動(dòng)切換線(xiàn)程)。
二、 System.Timers.Timer
間隔1秒執(zhí)行一次
using System.Timers;
class Program
{
static void Main()
{
var timer = new System.Timers.Timer(interval: 1000);
timer.Elapsed += (sender, e) => Console.WriteLine($"觸發(fā)時(shí)間: {e.SignalTime:T}");
timer.AutoReset = true;
timer.Start();
Console.ReadLine();
timer.Stop();
}
}
每天23點(diǎn)59分59秒執(zhí)行一次任務(wù)
using System.Timers;
class DailyTask
{
static Timer timer;
static void Main()
{
SetTimer();
Console.WriteLine("定時(shí)服務(wù)已啟動(dòng)...");
}
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} 執(zhí)行每日任務(wù)");
timer.Interval = TimeSpan.FromDays(1).TotalMilliseconds;
};
timer.Start();
}
}
基于事件(Elapsed 事件),代碼更易讀。
支持自動(dòng)重置(AutoReset 屬性控制是否循環(huán))。
可綁定到 UI 線(xiàn)程(通過(guò) SynchronizingObject,僅 WinForms)。
適合需要事件機(jī)制的場(chǎng)景(如 UI 定時(shí)更新)。
三、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線(xiàn)程創(chuàng)建
默認(rèn)Interval為1秒更新
MVVM模式需實(shí)現(xiàn)INotifyPropertyChanged接口
兩種實(shí)現(xiàn)方式各有適用場(chǎng)景,MVVM更適合復(fù)雜業(yè)務(wù)
注意避免直接在其他線(xiàn)程修改UI元素,這是選擇DispatcherTimer而非System.Timers.Timer的主要原因。如需動(dòng)態(tài)調(diào)整間隔時(shí)間,可通過(guò)修改Interval屬性實(shí)現(xiàn)
四、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 語(yǔ)法糖
提供任務(wù)取消(CancellationToken)
支持任務(wù)延續(xù)(ContinueWith)
并行任務(wù)處理(Task.WhenAll/WhenAny)
?與DispatcherTimer的區(qū)別?:
Tasks 是通用的異步編程模型
DispatcherTimer 專(zhuān)為UI線(xiàn)程定時(shí)器設(shè)計(jì)
Tasks 不自動(dòng)關(guān)聯(lián)UI線(xiàn)程上下文
閱讀原文:原文鏈接
該文章在 2025/6/17 13:49:24 編輯過(guò)