首页 > 解决方案 > 在 BackgroundService 上使用 ExecuteAsync 的 StopAsync

问题描述

我正在使用托管服务进行一些长时间运行的操作(检查打开的连接)。

使用 IHostedService 和 BackgroundService 类在微服务中实现后台任务的示例中,有两行在应用程序关闭时记录信息(在列出的代码中双引号)

但在我的场景中,我永远无法获得第二个日志信息?我想知道如果无法访问,为什么微软会放置第二行日志记录。谁能给我解释一下?

public class GracePeriodManagerService : BackgroundService {        
    private readonly ILogger<GracePeriodManagerService> _logger;
    private readonly OrderingBackgroundSettings _settings;

    private readonly IEventBus _eventBus;

    public GracePeriodManagerService(IOptions<OrderingBackgroundSettings>> settings,
                                     IEventBus eventBus,
                                     ILogger<GracePeriodManagerService> logger)
    {
        //Constructor’s parameters validations...       
    }

    protected override async Task ExecuteAsync(CancellationToken stoppingToken)
    {
        _logger.LogDebug($"GracePeriodManagerService is starting.");

         stoppingToken.Register(() => 
                _logger.LogDebug($" GracePeriod background task is stopping."));

        while (!stoppingToken.IsCancellationRequested)
        {
            _logger.LogDebug($"GracePeriod task doing background work.");

            // This eShopOnContainers method is querying a database table 
            // and publishing events into the Event Bus (RabbitMS / ServiceBus)
            CheckConfirmedGracePeriodOrders();

            await Task.Delay(_settings.CheckUpdateTime, stoppingToken);
        }

         _logger.LogDebug($"GracePeriod background task is stopping.");

    }

    protected override async Task StopAsync (CancellationToken stoppingToken)
    {
           // Run your graceful clean-up actions
    } 
}

标签: c#asp.net-core-2.1

解决方案


推荐阅读