关于实现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:下图中红框中的描述。

 

 

 

解惑:

翻看源码,发现如下图的源码

(1)BackgroundService.cs源码

 

 

 (2)Host.cs 源码

 

 

 

 参考代码:

  //第一种
    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);
            }
        }
    }

 

posted @ 2022-01-14 15:32  会搬砖的好孩子  阅读(102)  评论(0)    收藏  举报