如何手动取消 .NET Core IHostedService 后台任务?

7

我希望在Startup.cs完成后进行一些异步工作。 我通过扩展BackgroundService 实现了一些异步任务的后台服务。

我的问题是如何在我决定的时间取消运行任务? 我只能看到文档中延迟下一个周期的示例。

我尝试手动执行StopAsync,但while循环会无限执行(令牌未被取消,虽然我觉得应该被取消,因为我已经将令牌传递给了StopAsync,而且实现看起来就像它应该这样做)。

这是一些简化的代码:

public class MyBackgroundService : BackgroundService
{
    private readonly ILogger<MyBackgroundService> _logger;

    public MyBackgroundService(ILogger<MyBackgroundService> logger)
    {
        _logger = logger;
    }

    protected override async Task ExecuteAsync(CancellationToken stoppingToken)
    {
        _logger.LogInformation("MyBackgroundService is starting.");

        while (!stoppingToken.IsCancellationRequested)
        {
            _logger.LogInformation("MyBackgroundService task doing background work.");

            var success = await DoOperation();
            if (!success)
            {
                // Try again in 5 seconds
                await Task.Delay(5000, stoppingToken);
                continue;
            }

            await StopAsync(stoppingToken);
        }
    }
}
1个回答

5

我并没有完全明白ExecuteAsync只会被框架调用一次这个事实。因此,答案很简单,当你完成时跳出循环即可。

protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
    _logger.LogInformation("MyBackgroundService is starting.");

    while (!stoppingToken.IsCancellationRequested)
    {
        _logger.LogInformation("MyBackgroundService task doing background work.");

        var success = await DoOperation();
        if (!success)
        {
            // Try again in 5 seconds
            await Task.Delay(5000, stoppingToken);
            continue;
        }

        break;
    }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接