title: Windows Service using .net core BackgroundService, how to gracefully stop?
body: <p>I'm developing a windows service using .Net Core 3.1</p>
  <p>Lots of online resource suggesting me to use <code>BackgroundService</code> for it. Problem is I cannot get the service to be stopped gracefully, by just overriding <code>ExecuteAsync</code> method.</p>
  <p>The codes setup for testing is very simple:</p>
  <pre class="lang-cs prettyprint-override"><code>public class MyService: BackgroundService
  {
      protected override async Task ExecuteAsync(CancellationToken stoppingToken)
      {
          Console.WriteLine($&quot;Service started at {DateTimeOffset.Now}&quot;);
          await DoLongRunningWork(stoppingToken);
      }
  
      public override async Task StopAsync(CancellationToken cancellationToken)
      {
          Console.WriteLine(&quot;Service is being stopped...&quot;);
          await base.StopAsync(cancellationToken);
          Console.WriteLine(&quot;Service stopped at {DateTimeOffset.Now}&quot;);
      }
  
      private static async Task DoLongRunningWork(CancellationToken token)
      {
          Console.WriteLine(&quot;I'm working...&quot;);
          while (!token.IsCancellationRequested)
          {
              Console.WriteLine($&quot;\t... doing work ...&quot;);
              await Task.Delay(1000, token);
          }
  
          // THE BELOW LINE IS NEVER REACHED. i.e The line &quot;Cancel requested? True&quot; is never logged out...
          Console.WriteLine($&quot;Cancel requested? {token.IsCancellationRequested}&quot;);
      }
  }
  </code></pre>
  <p>And the <code>Main</code> method</p>
  <pre class="lang-cs prettyprint-override"><code>
  static void Main(string[] args)
  {
      Console.WriteLine(&quot;Starting My Service...&quot;);
      Host.CreateDefaultBuilder(args)
          .UseWindowsService()
          .ConfigureServices(services =&gt;
          {
              services.AddHostedService&lt;MyService&gt;();
          })
          .Build()
          .Run();
  }
  </code></pre>
  <p>One thing I can do is implementing my own <code>Stop</code> method and calling it in my override <code>StopAsync</code>. But I'm curious why this simple setup didn't work as expected.</p>
  <p>I have read the <a href="https://github.com/dotnet/extensions/blob/release/3.1/src/Hosting/Abstractions/src/BackgroundService.cs" rel="nofollow noreferrer">BackgroundService.cs</a> source code, it looks like it should work the way I expected (i.e. this line <code>Cancel requested? True</code> should be logged out but it didn't...</p>
  <p>I have tried both running it as a console app and stopping it using <code>Ctrl+C</code>, as well as installed it as Windows Service and using <code>service.msc</code> to control it. Same behaviour (i.e. no gracefully shutdown...)</p>
  <p>Any helps are much appreciated!</p>