Skip to content

BackgroundService handles Exceptions getting thrown differently when tasks are not faulted vs faulted #36388

@PureKrome

Description

@PureKrome

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 ExecuteAsync is handled, the app will crash.
  • If an exception is thrown during ExecuteAsync but before the first await is called, the app will crash.
  • If an exception is thrown during ExecuteAsync but during or after the first await is 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.

Metadata

Metadata

Assignees

No one assigned

    Labels

    area-Extensions-HostingenhancementProduct code improvement that does NOT require public API changes/additions

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions