title: How do I (gracefully) shut down a worker service from within itself?
body: <p>I'm using the .NET Core 3.1 worker service template to build a Windows Service.</p>
  
  <p>I gather that the basic flow should be handled within <code>ExecuteAsync</code>, roughly like so:</p>
  
  <pre class="lang-cs prettyprint-override"><code>        protected override async Task ExecuteAsync(CancellationToken stoppingToken)
          {
              while (!stoppingToken.IsCancellationRequested)
              {
                  try
                  {
                      _Logger.LogInformation("Worker running at: {time}", DateTimeOffset.Now);
  
                      await SomeMethodThatDoesTheWork(stoppingToken);
                  }
                  catch (Exception ex)
                  {
                      _Logger.LogError(ex, "Global exception occurred. Will resume in a moment.");
                  }
  
                  await Task.Delay(TimeSpan.FromSeconds(10), stoppingToken);
              }
          }
  </code></pre>
  
  <p>I'm trying to properly signal from within the process that I want the app to shut down.</p>
  
  <p>When stopping the service, I assume <code>StopAsync()</code> gets called. This seems to work fine. So I thought <code>await StopAsync()</code> would do the trick, but afterwards, <code>ExecuteAsync</code> still keeps running (so I'm guessing <code>StopAsync</code> won't request cancellation, and you're not supposed to call it yourself).</p>
  
  <p>So I amended my loop with another bool:</p>
  
  <pre class="lang-cs prettyprint-override"><code>            while (!stoppingToken.IsCancellationRequested &amp;&amp; !_ShuttingDown)
  
  </code></pre>
  
  <p>This does exit the loop, and never enters <code>ExecuteAsync</code> again. However, the app just keeps on running. According to the debugger, it just stays on <code>host.Run()</code>.</p>
  
  <p>How do I signal to the application host that I want to shut down?</p>