dotnet/runtime

Hosted services are started even though the application is instructed to stop.

オープン

#51,613 opened on 2021/04/21

 (10 件のコメント) (0 件のリアクション) (0 人の担当者)C# (5,445 件のフォーク)batch import
area-Extensions-Hostinghelp wanted

Repository metrics

Stars
 (17,886 個のスター)
PR merge metrics
 (平均マージ 12d 11h) (30d で 661 merged PRs)

説明

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!

コントリビューターガイド