如何在C#中无需手动调用自动每100ms触发事件处理器?
C#实现定时自动触发任务的方案
在C#里有多种无需手动调用、自动按固定间隔触发任务的方式,以下是几种常用方案:
1. 使用System.Timers.Timer
这是最常用的定时组件之一,适配大多数桌面或服务端场景:
using System; using System.Timers; public class TimerExample { private Timer _timer; public void StartTimer() { // 初始化Timer,设置触发间隔为100ms _timer = new Timer(100); // 绑定定时触发的事件处理器 _timer.Elapsed += OnTimerElapsed; // 设置为重复触发 _timer.AutoReset = true; // 启动定时器 _timer.Start(); } private void OnTimerElapsed(object sender, ElapsedEventArgs e) { // 这里编写每隔100ms需要执行的任务逻辑 Console.WriteLine($"任务执行于:{DateTime.Now:HH:mm:ss.fff}"); } public void StopTimer() { _timer?.Stop(); _timer?.Dispose(); } }
注意:Elapsed事件在ThreadPool线程上触发,若任务涉及UI操作,需切换到UI线程(比如WPF用Dispatcher.Invoke,WinForms用Invoke)。
2. 使用System.Threading.Timer
更轻量的定时器,适合简单后台任务场景:
using System; using System.Threading; public class ThreadingTimerExample { private Timer _timer; public void StartTimer() { // 参数说明:回调方法、状态对象、首次触发延迟、重复触发间隔 _timer = new Timer(OnTimerCallback, null, 0, 100); } private void OnTimerCallback(object state) { // 执行定时任务逻辑 Console.WriteLine($"任务执行于:{DateTime.Now:HH:mm:ss.fff}"); } public void StopTimer() { _timer?.Change(Timeout.Infinite, Timeout.Infinite); _timer?.Dispose(); } }
3. 使用PeriodicTimer(.NET 6+)
.NET 6引入的异步定时器,适配现代异步编程场景:
using System; using System.Threading; using System.Threading.Tasks; public class PeriodicTimerExample { public async Task RunTimerAsync(CancellationToken cancellationToken) { using var timer = new PeriodicTimer(TimeSpan.FromMilliseconds(100)); while (await timer.WaitForNextTickAsync(cancellationToken)) { // 执行异步定时任务 Console.WriteLine($"任务执行于:{DateTime.Now:HH:mm:ss.fff}"); } } }
可通过CancellationToken控制任务停止,适合异步流程中使用。
4. 后台服务场景(ASP.NET Core/.NET Worker Service)
如果是在后台服务中需要定时任务,可继承BackgroundService:
using Microsoft.Extensions.Hosting; using System; using System.Threading; using System.Threading.Tasks; public class TimedHostedService : BackgroundService { protected override async Task ExecuteAsync(CancellationToken stoppingToken) { using var timer = new PeriodicTimer(TimeSpan.FromMilliseconds(100)); while (!stoppingToken.IsCancellationRequested && await timer.WaitForNextTickAsync(stoppingToken)) { // 执行后台定时任务 Console.WriteLine($"任务执行于:{DateTime.Now:HH:mm:ss.fff}"); } } }
将该服务注册到DI容器后,服务启动时会自动运行定时任务。
内容的提问来源于stack exchange,提问作者DharuvVerma21
相关产品推荐
相关产品推荐

