admin管理员组

文章数量:1123144

This is perhaps a misunderstanding how a BackgroundService works in comparison to the older full framework Windows Service implementations, but when attempting to call host.StartAsync(), after a call to host.StopAsync(), StartAsync fails with the error: System.OperationCanceledException: 'The operation was canceled.'

Program.cs

IHost host = Host.CreateDefaultBuilder(args)
  .ConfigureServices(services => {
    services.AddHostedService<TestWorker>();
  })
  .Build();

host.RunAsync();

while (true) {
  Thread.Sleep(5000);
  await host.StopAsync();
  Thread.Sleep(5000);
  await host.StartAsync();
}

TestWorker.cs

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

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

  protected override async Task ExecuteAsync(CancellationToken stoppingToken) {
    while (!stoppingToken.IsCancellationRequested) {
      _logger.LogInformation("Worker running at: {time}", DateTimeOffset.Now);
      await Task.Delay(1000, stoppingToken);
    }
  }
}

Can someone explain why this is, and what the proper way to programmatically start a BackgroundService is after it as been programmatically stopped?

本文标签: cRestarting a basic NET BackgroundService fails with SystemOperationCancelledExceptionStack Overflow