Hosted services are started even though the application is instructed to stop.
#51,613 opened on Apr 21, 2021
Repository metrics
- Stars
- (17,886 stars)
- PR merge metrics
- (Avg merge 12d 11h) (661 merged PRs in 30d)
Description
Description
As Microsoft.Extensions.Hosting.Internal.Host starts, it resolves all registered instances of IHostedService and starts them in sequence. If a hosted service stops the application (using IHostApplicationLifetime.StopApplication()), the remaining hosted services are still started (that is StartAsync is called), despite the fact that the application is instructed to shut down.
This can results in a combination of the following behaviors:
- If any of the remaining hosted services checks the provided cancellation token and throws an exception, it propagates and results in an unhandled exception unless the user wraps the start call in try/catch. This feels unexpected, as the stopping should be considered graceful.
- If the remaining hosted services does not check the cancellation token, time and resources may be spent starting components that will just be stopped shortly after. This does not scale well if there are "a lot" of registered hosted services that takes "long" time to start.
I think it would make sense to check the IHostApplicationLifetime.ApplicationStopping cancellation token after each started hosted service and if it is triggered, gracefully exit the application.
One could also argue that ThrowIfCancellationRequested should be called on the cancellation token passed to StartAsync after each started service.
Looking forward hearing your thoughts on this!