.NET 中的后台服务允许在后台独立于主应用程序线程运行任务。这对于需要连续或定期运行而不阻塞主应用程序流的任务至关重要。
在.NET 8中,IHostedService 和 BackgroundService 两个核心接口的引入,提高处理定时任务的能力。简化了定时任务、后台处理作业以及定期维护任务的实现过程。
IHostedService接口提供了一个基本的框架,允许自定义后台服务的启动和停止逻辑。通过实现该接口,在应用程序启动时自动运行,并在应用程序关闭时结束。
而 BackgroundService 类则是对 IHostedService 接口的进一步封装,它专为需要长时间运行的任务而设计。
介绍
IHostedService
IHostedService 是一个简单的接口,用于实现后台服务。当需要实现自定义的托管服务时,可以通过实现这个接口来创建。
该接口定义了两个方法:StartAsync(CancellationToken cancellationToken) 和 StopAsync(CancellationToken cancellationToken),分别用于启动和停止服务。
注册服务
Program.cs 中添加配置,Startup.cs 注册服务。
public async void ConfigureServices(IServiceCollection services)
{
services.AddControllersWithViews();
services.AddControllers();
services.AddSwaggerGen();
services.AddHostedService<CustomHostedService>();
}
2、创建服务接口
创建一个类,该类继承 IHostedService 接口,并实现该接口成员。
public class CustomHostedService : IHostedService, IDisposable
{
private Timer? _timer;
public Task StartAsync(CancellationToken cancellationToken)
{
Console.WriteLine("Custom Hosted Service start work");
_timer = new Timer(DoWork, null, TimeSpan.Zero, TimeSpan.FromSeconds(5));
return Task.CompletedTask;
}
private void DoWork(object? state)
{
Console.WriteLine("Custom Hosted Service is working");
}
public Task StopAsync(CancellationToken cancellationToken)
{
Console.WriteLine("Custom Hosted Service is stopping");
return Task.CompletedTask;
}
public void Dispose()
{
_timer?.Dispose();
}
}
}
应用在运行后,会去执行 StartAsync 函数,应用关闭执行 StopAsync,由于这里使用的定时器,所以每过5秒都会执行一次 DoWork 函数。
BackgroundService
BackgroundService 是一个抽象类,它继承自 IHostedService 并提供了更简洁的方式来编写后台服务。它通常用于需要长时间运行的任务,如监听器、工作队列处理器等。通过重写 ExecuteAsync(CancellationToken stoppingToken)方法,可以在其中编写任务的逻辑。ExecuteAsync方法会循环在后台执行,直到服务停止。
public async void ConfigureServices(IServiceCollection services)
{
services.AddControllersWithViews();
services.AddControllers();
services.AddSwaggerGen();
services.AddHostedService<CustomBackgroundService>();
}
public class CustomBackgroundService : BackgroundService
{
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
Console.WriteLine("Custom Background Service start work");
while (!stoppingToken.IsCancellationRequested)
{
Console.WriteLine("Custom Background Service is working");
await Task.Delay(TimeSpan.FromSeconds(5), stoppingToken);
}
Console.WriteLine("Custom Background Service is stopping");
}
}
主要区别
-
抽象级别:
IHostedService
:需要手动实现启动和停止逻辑。BackgroundService
:通过提供具有要重写的单个方法的基类来简化实现。
-
使用案例:
IHostedService
:适用于需要对服务生命周期进行精细控制的更复杂的方案。BackgroundService
:非常适合受益于减少样板代码的更简单、长时间运行的任务。
结论
通过根据您的需求选择适当的抽象,您可以有效地在应用程序中实现和管理长时间运行的操作。这些新功能增强了创建响应迅速、可伸缩且可维护的 .NET 应用程序的能力。