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

Dav*_*nce 7 c# .net-core asp.net-core

我想在 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);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

Dav*_*nce 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;
    }
}
Run Code Online (Sandbox Code Playgroud)