title: Manage cancellation on the Token in a .NET Core 3.0 Worker Service
body: <p>I'm developing my first .NET Core 3.0 Worker Service to run it as a Windows Service.</p>
  
  <p>Here there is the code I used for the test.</p>
  
  <p>Debugging I see that stopping the windows service, the StopAsync() will be executed, but the ExecuteAsync() terminates due to the exception OperationCanceledException (thrown from the line Task.Delay(1000, stoppingToken)).
  Of course I can catch it but what I would like to do is complete the method flow in order to exit gracefully.</p>
  
  <p><strong>Is there any way to avoid the exception and just exit according to the while condition?</strong></p>
  
  <pre><code>namespace Enerj.MyAppCore.WorkerService
  {
      public class Worker : BackgroundService
      {
          private readonly ILogger&lt;Worker&gt; _logger;
          bool exit = false;
  
          public Worker(ILogger&lt;Worker&gt; logger)
          {
              _logger = logger;
              _logger.LogInformation("ctor");
          }
  
          public override async Task StartAsync(CancellationToken cancellationToken)
          {
              _logger.LogInformation("Start");
              await base.StartAsync(cancellationToken);
          }
  
          protected override async Task ExecuteAsync(CancellationToken stoppingToken)
          {
              while (!stoppingToken.IsCancellationRequested)
              {
                  _logger.LogInformation("Worker running at: {time}", DateTimeOffset.Now);
                  await Task.Delay(1000, stoppingToken);
              }
              System.Diagnostics.Debugger.Break();
          }
  
          public override async Task StopAsync(CancellationToken cancellationToken)
          {
              _logger.LogInformation("Stopping");
              await Task.CompletedTask;
          }
      }
  }
  </code></pre>