Hosted services are started even though the application is instructed to stop.
#51,613 建立於 2021年4月21日
倉庫指標
- Star
- (17,886 star)
- PR 合併指標
- (平均合併 12天 11小時) (30 天內合併 661 個 PR)
描述
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!