title: ASP.NET Core hosted service ExecuteAsync() method doesn't complete
body: <p>Can anyone help me understand why &quot;WHY DOES THIS NEVER GET CALLED?&quot; never gets logged to the console when the application is shutdown in the following code example?</p>
  <pre class="lang-cs prettyprint-override"><code>public class TestBackgroundService : BackgroundService
  {
      protected override async Task ExecuteAsync(CancellationToken stoppingToken)
      {
          System.Console.WriteLine(&quot;Executing test background service...&quot;);
  
          await Task.Delay(Timeout.Infinite, stoppingToken);
  
          System.Console.WriteLine(&quot;WHY DOES THIS NEVER GET CALLED?&quot;);
      }
  }
  </code></pre>
  <p>This is registered as a hosted service in the <code>Startup</code> class, as usual:</p>
  <pre class="lang-cs prettyprint-override"><code>public void ConfigureServices(IServiceCollection services)
  {
      services.AddHostedService&lt;TestBackgroundService&gt;();
  }
  </code></pre>
  <p>My expectation was that when the application starts shutting down, the <code>stoppingToken</code> is triggered and the call to <code>Task.Delay()</code> should return, then the rest of the <code>ExecuteAsync()</code> method would execute during the default five second shutdown timeout, before the application forcefully shuts down.</p>
  <p>The console shows &quot;Executing test background service...&quot; as expected, but not &quot;WHY DOES THIS NEVER GET CALLED?&quot;.</p>
  <p>For reference, the base BackgroundService class can be seen and read about here, with an example: <a href="https://docs.microsoft.com/en-us/dotnet/architecture/microservices/multi-container-microservice-net-applications/background-tasks-with-ihostedservice#implementing-ihostedservice-with-a-custom-hosted-service-class-deriving-from-the-backgroundservice-base-class" rel="nofollow noreferrer">https://docs.microsoft.com/en-us/dotnet/architecture/microservices/multi-container-microservice-net-applications/background-tasks-with-ihostedservice#implementing-ihostedservice-with-a-custom-hosted-service-class-deriving-from-the-backgroundservice-base-class</a></p>