Search code examples
.net-corewindows-services.net-core-3.0background-service

Windows service using BackgroundService cannot be stopped


I'm using a Net Core 3.X BackgroundService and after publishing my code, I've installed the executable generated as a Windows Service.

On my ExecuteAsync method I have some code like this:

protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
    while (!stoppingToken.IsCancellationRequested)
    {
        //do something

        if(someConditionIsTrue)
        {
            await this.StopAsync(new CancellationToken());
        }
    }
}

That manual call on StopAsync stops the execution and exits from while loop, but when I go to services.msc I see that my Windows Service is still in running state although is not executing anything.

How can I stop the service automatically and not calling to "cmd \c sc stop..."?

Thanks


Solution

  • Your BackgroundService is stopping correctly, but the application is not being stopped.

    To stop the application from a background service, inject a IHostApplicationLifetime and call it as such:

    protected override async Task ExecuteAsync(CancellationToken stoppingToken)
    {
      while (!stoppingToken.IsCancellationRequested)
      {
        //do something
    
        if (someConditionIsTrue)
        {
          _hostApplicationLifetime.StopApplication();
        }
      }
    }
    

    You don't need to call this.StopAsync because that will (eventually) be called by StopApplication.