How are hosted services supposed to behave in relation to HTTP server shutdown process? #67236
Replies: 1 comment
|
My understanding is that this is effectively how it works today with the Generic Host: hosted services are started in registration order and stopped in reverse registration order. Since the web server is registered as a hosted service as part of the web host setup, that means it will normally be stopped before earlier user registered hosted services. In practice, that gives the HTTP server a chance to stop accepting new requests and drain in flight work before dependent background services are stopped. So your reasoning makes sense to me: if an in flight HTTP request depends on one of your hosted services, stopping the server first is the safer shutdown order. I would be careful about relying on the server always being registered last as a permanent implementation detail, though. The more stable assumption is the hosted service lifecycle rule: start order is registration order, stop order is reverse registration order, unless concurrent hosted service shutdown has been enabled through host options. In short: yes, the behavior you observed is consistent with the current hosting model, but I would want the docs to state this explicitly before treating it as a long term ASP.NET Core contract. |
Uh oh!
There was an error while loading. Please reload this page.
If I look at StartAsync it clearly states that all of the
IHostedServicestart sequentially and in order of registration.On top of that, it says that the HTTP processing pipeline does start only after all hosted services have started.
Unfortunately StopAsync does NOT provide such level of information.
By looking at the source code and debugging, I can see that the HTTP server is just another
IHostedServicewhich is always registered as the last one.This means to me that all of the
IHostedServiceswill be stopped only after the HTTP server finished draining all in-flight requests.This makes sense to me because an HTTP call may depend on one of those background services to properly finish the in-flight request.
Is this correct? Can we trust this behavior forever?
All reactions