-
Notifications
You must be signed in to change notification settings - Fork 5.3k
Description
I think how exceptions are handled with BackgroundService class is a bit confusing and may require some discussion.
- If an exception is thrown during startup (e.g. in Main) and before
ExecuteAsyncis handled, the app will crash. - If an exception is thrown during
ExecuteAsyncbut before the firstawaitis called, the app will crash. - If an exception is thrown during
ExecuteAsyncbut during or after the firstawaitis called, the app will ... semi-hang? It stop processing ... but ... Ctrl-C does successfully start the app gracefully terminating.
Now - I hope i have the above steps/scenario's right -- I might have fudged something (async/await/ task contexts, etc are my weak points).
So the problem here is about the inconsistency about what an exception should be doing in a BackgroundService. Should it crash the host (assuming no top level try/catch in Main)? or get swallowed? Maybe the issue is really about documentation (as the code is totally fine).
This issue arose when I started a conversation in the "ASP.NET slack" group when I was trying to handle an exception getting thrown in side the ExecuteAsync method and bubbling that upwards.
To quote some of the summaries of this convo:
@davidfowl [7:06 PM]
great discussion
heh
it could suppress both and if you wanted to get exceptions, then you override StartAsync and put logic there
--
@chrisvanderpennen [7:13 PM]
theres imo three scenarios that need covering:
i don't want any exceptions in this to stop my host
i want an exception during init to stop the host startup, but runtime exceptions are ok
i want a runtime exception to stop my host
@davidfowl [7:30 PM]
somebody file a bug
so CC'ing @poke @gulbanana @chrisvanderpennen and @davidfowl who were in the convo.
- I think the issue subject might need to be refactored.
- happy to edit the main body of this issue, where i got my facts wrong.
- This issue needs the famous tag 'fowler' (fowler has issues). :)
edit: this was a sample gist I tried to make to also test/repo this problem.