关于实现IHostedService接口的一些疑惑
参考资料:
1、实现IHostedSerivce接口:https://docs.microsoft.com/zh-cn/dotnet/core/extensions/timer-service
2、在 ASP.NET Core 3.1 中使用托管服务实现后台任务:https://docs.microsoft.com/zh-cn/aspnet/core/fundamentals/host/hosted-services?view=aspnetcore-3.1&tabs=visual-studio
正文:
疑惑1:下图中红框中的描述。

解惑:
翻看源码,发现如下图的源码


参考代码:
//第一种 public class CatService : BackgroundService { protected override Task ExecuteAsync(CancellationToken stoppingToken) { var task = WhileMehtodAsync(stoppingToken); if (task.IsCompleted) { return task; } return Task.CompletedTask; } private async Task WhileMehtodAsync(CancellationToken stoppingToken) { while (!stoppingToken.IsCancellationRequested) { Console.WriteLine("CatService"); await Task.Delay(500); } } }
//第二种 public class CatService : BackgroundService { protected override async Task ExecuteAsync(CancellationToken stoppingToken) { await WhileMehtodAsync(stoppingToken); } private async Task WhileMehtodAsync(CancellationToken stoppingToken) { while (!stoppingToken.IsCancellationRequested) { Console.WriteLine("CatService"); await Task.Delay(500); } } }
//第三种 public class CatService : BackgroundService { protected override async Task ExecuteAsync(CancellationToken stoppingToken) { while (!stoppingToken.IsCancellationRequested) { Console.WriteLine("CatService"); await Task.Delay(500); } } private async Task WhileMehtodAsync(CancellationToken stoppingToken) { while (!stoppingToken.IsCancellationRequested) { Console.WriteLine("CatService"); await Task.Delay(500); } } }

浙公网安备 33010602011771号