ASP.NET Core 中的托管服务如何运行后台任务?

来源:这里教程网 时间:2026-02-21 17:28:01 作者:

在 ASP.NET Core 中,托管服务(Hosted Services)通过实现 IHostedService 接口来运行后台任务。这类服务会在应用启动时自动开始,并在应用关闭时优雅停止,非常适合执行轮询、定时任务或持续运行的工作。

实现 IHostedService 接口

要创建一个后台任务,需定义一个类实现 IHostedService,该接口包含两个核心方法:

StartAsync(CancellationToken):在应用启动后调用,用于启动后台任务。 StopAsync(CancellationToken):在应用关闭时调用,允许任务安全退出。

通常,StartAsync 中会启动一个后台循环或定时器,而 StopAsync 则通知任务停止并等待完成。

使用 BackgroundService 基类

更推荐的方式是继承 BackgroundService 抽象类,它已实现 IHostedService 并提供了一个可重写的 ExecuteAsync(CancellationToken) 方法。

这个方法接收一个取消令牌,在应用关闭时触发,可用于控制任务的生命周期。

例如:
public class MyBackgroundService : BackgroundService
{
    protected override async Task ExecuteAsync(CancellationToken stoppingToken)
    {
        while (!stoppingToken.IsCancellationRequested)
        {
            // 执行你的后台逻辑
            await DoWorkAsync(stoppingToken);
            
            // 暂停一段时间,比如每10秒执行一次
            await Task.Delay(10000, stoppingToken);
        }
    }
}

将服务注册到依赖注入容器中:

builder.Services.AddHostedService<MyBackgroundService>();

处理定时任务

如果需要按固定时间间隔运行任务,可以结合 TimerPeriodicTimer(.NET 6+)使用。

PeriodicTimer 更现代且与取消令牌集成更好:

using var timer = new PeriodicTimer(TimeSpan.FromSeconds(30));
while (await timer.WaitForNextTickAsync(stoppingToken))
{
    if (!stoppingToken.IsCancellationRequested)
        await RunScheduledJobAsync(stoppingToken);
}

注意事项

编写托管服务时要注意以下几点:

避免在构造函数中做耗时操作,可能影响应用启动。 始终监听取消令牌,确保能优雅关闭。 异常未被捕获可能导致任务终止,建议在循环内加 try-catch。 若需访问数据库或HTTP客户端,应通过依赖注入获取服务实例。 基本上就这些。只要正确实现和注册,托管服务就能可靠地运行后台任务。

相关推荐