dotnet/runtime

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

Open

#51.613 geöffnet am 21. Apr. 2021

Auf GitHub ansehen
 (10 Kommentare) (0 Reaktionen) (0 zugewiesene Personen)C# (5.445 Forks)batch import
area-Extensions-Hostinghelp wanted

Repository-Metriken

Stars
 (17.886 Stars)
PR-Merge-Metriken
 (Durchschn. Merge 12T 11h) (661 gemergte PRs in 30 T)

Beschreibung

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!

Contributor Guide