Loading

dot net core使用BackgroundService运行一个后台服务

不管是在控制台程序还是asp.net core程序中,我们经常会有用到一个需要长时间运行的后台任务的需求。通常最直觉的方式是使用Thread实例来新建一个线程,但是这样需要自行管理线程的启动和停止。

.net core中提供了一个继承自IHostedService的基类BackgroudService能够方便地实现一个长程的后台任务。

为了使用这个基类进行开发,我们需要向项目中添加包:Microsoft.Extensions.Hosting
然后新建一个后台任务类AppHostedService并实现ExecuteAsync方法即可。

一个简单的ExecuteAsync任务实现

protected override async Task<object> ExecuteAsync(CancellationToken stoppingToken)
{
	int loop = 0;
	while (!stoppingToken.IsCancellationRequested) {
		try {
			Console.WriteLine("Backgroun service working...");
			await Task.Delay(5000, stoppingToken);
		} catch(TaskCanceledException exception)
		{
			Console.WriteLine($"TaskCanceledException Error: {exception.Message}");
		}
	}
	return Task.CompletedTask;
}

另外在主程序中使用Host.CreateDefaultBuilder()来创建运行程序的托管服务并加入我们刚刚创建的AppHostedService

await Host.CreateDefaultBuilder()
    .UseConsoleLifetime()
    .ConfigureServices((context, services) => {
        services.AddHostedService<AppHostService>();
    })
    .RunConsoleAsync();

创建完成后编译运行,将看到托管服务的启动输出信息和在任务中周期性输出的信息。完整代码见Gist

Hello, World!
Start Async AppHostService
Backgroun service working...
info: Microsoft.Hosting.Lifetime[0]
      Application started. Press Ctrl+C to shut down.
info: Microsoft.Hosting.Lifetime[0]
      Hosting environment: Production
info: Microsoft.Hosting.Lifetime[0]
      Content root path: C:\Users\ZhouXinfeng\tmp\hostservice\bin\Debug\net8.0
Background service working...
Background service working...
Background service working...
Background service working...
Background service working...
Background service working...
Background service working...
Background service working...

参考链接

  1. .NET Core 实现后台任务(定时任务)BackgroundService(二)(https://www.cnblogs.com/ysmc/p/16468560.html)
  2. Background tasks with hosted services in ASP.NET Core
  3. The "correct" way to create a .NET Core console app without background services
posted @ 2024-05-27 15:24  mrchip  阅读(336)  评论(0编辑  收藏  举报