You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
BackgroundService handles Exceptions getting thrown differently when tasks are not faulted vs faulted #36388
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 ExecuteAsyncbut before the first await is called, the app will crash.
If an exception is thrown during ExecuteAsyncbut 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
imo the bug is that BackgroundService deliberately defers exceptions which are stashed in the Task, but can still be brought down by a Task-returning function which throws before or instead of awaiting. it’d be more consistent if it also used try-catch to intercept and store exceptions from that first section of the state machine.
the “semi-hang” might just be the intended behaviour of ConsoleLifetime though.
here’s one way that the exceptions could be given a consistent treatment, using a handler function which relies on AsyncTaskMethodBuilder to queue continuations onto the threadpool if they do occur:
I would have expected worker services to have a built-in notion of global exception handling, but I guess not (yet)?
Anyway, here's what I do for now:
protectedoverrideasyncTaskExecuteAsync(CancellationTokenstoppingToken){while(!stoppingToken.IsCancellationRequested){try{_logger.LogInformation("Worker running at: {time}",DateTimeOffset.Now);// actual stuff happens here}catch(Exceptionex){// waiting on https://github.com/aspnet/Extensions/issues/813_Logger.LogError(ex,"Global exception occurred. Will resume in a moment.");}awaitTask.Delay(1000,stoppingToken);}}
Why doesn't that make sense? I'd certainly expect if I have a background service running that fails at some point and I haven't caught the error, that it would bring the application down.
He does seem to be rather adamant about that. I personally think that's the wrong decision (particularly for worker services you can end up in a situation where the entire process just does.. nothing and you don't know unless you have alerts on your logs) - but hey ¯\(ツ)/¯
Let me try to paint the worst case scenario for each "mode". Scenario 1. You have a non-important Service and the default is to crash on unhandled errors
This brings your application down. You go look at the logs, and you see that it's your NotImportantService that brought the house down. You curse under your breath, and wrap it in a dummy catch or a Polly retry or whatever. Worst case is you get some downtime once.
Scenario 2. You have an important service, and the default is to just let it die
Your service runs some stuff every hour. At some point data stops coming through. You look at the server - it's running fine (and you don't know that a crashing BackgroundService doesn't crash the server). You look at the logs. Finding anything is hard (impossible without this new PR), because the service could have crashed a long time ago. You mutter under your breath, and figure out how to properly close the application via IApplicationLifetime or similar.
I'm not exaggerating when I've seen people spend weeks re-writing stuff because they were unable to debug a silently crashing BackgroundService, and thought the process was gettign OOMKilled or similar.
All I'm saying is that the failure mode for Scenario 2 is much worse, which is why I think that crashing should be the default. Admittedly that calculation was more heavily skewed back when we didn't even have any logs.
But perhaps the right solution is for there to be no default - but forcing the user to explicitly specify "Should this backgroundservice crash the server on an uncaught error" - because I agree that there are both types of services.
Reacted by Tadas Šukys, escalonn, cwe1ss, Marc Selis, P-Storm, Hogne Vevle, nicchristeller, Rasmus Sigsgaard, Rasmus Sigsgaard, Markus H and 2 more
I have just been hit by this along with several colleagues. We have a long running background service pulling from a message queue (Google PubSub). The message queue service is started (await StartAsync) and completes only when manually stopped, or when an unrecovereable error occurs. This recently started periodically failing silently for long periods of time until a restart. And it took us a long time to figure out was a permission issue, even though an exception was thrown by StartAsync.
Our assumptions mirrors @GeeWee's thoughts, that an unhandled exception is exceptional, and will result in the application exiting. This has been my logic for many years, stemming from multiple sources (some listed below). If you need something to be resilient against exceptions, then it is an active choice you make, and wrap it in a try..catch. Having code swallow exceptions that are too vague is something that I point out again and again in code reviews, since there is a risk of hiding unknown future errors, and since I expect the runtime to catch any unhandled exceptions.
BackgroundService seems to flip this upside down, and now we have to actively handle unknown exceptions in every BackgroundService we implement.
I just want to do a shameless plug that I've implemented a tiny library BetterHostedServices that lets you inherit from CriticalBackgroundService which will end the application on an uncaught exception.
Hopefully this issue will get fixed in the core library but until then this is a band-aid solution.
Activity
gulbanana commentedon Nov 29, 2018
imo the bug is that BackgroundService deliberately defers exceptions which are stashed in the Task, but can still be brought down by a Task-returning function which throws before or instead of awaiting. it’d be more consistent if it also used try-catch to intercept and store exceptions from that first section of the state machine.
the “semi-hang” might just be the intended behaviour of ConsoleLifetime though.
gulbanana commentedon Nov 29, 2018
here’s one way that the exceptions could be given a consistent treatment, using a handler function which relies on AsyncTaskMethodBuilder to queue continuations onto the threadpool if they do occur:
https://github.com/gulbanana/local-async-example/blob/master/Program.cs
Merge pull request #813 from benaadams/threading-issue
muratg commentedon Jan 9, 2019
@davidfowl what's the work in 3.0 here?
cc @Tratcher
davidfowl commentedon Jan 10, 2019
A few targeted changes to BackgroundService.
analogrelay commentedon Mar 29, 2019
@davidfowl are you going to do this?
davidfowl commentedon Mar 30, 2019
Yes, I have a branch, I've just been lazy finishing it. I'll do it next week.
PureKrome commentedon Jul 30, 2019
Sadness -> this is now in
Backlogand will not ship withv3?analogrelay commentedon Jul 31, 2019
Correct. Unfortunately there was higher priority work that we had to bump this out for.
chucker commentedon Dec 18, 2019
I would have expected worker services to have a built-in notion of global exception handling, but I guess not (yet)?
Anyway, here's what I do for now:
10 remaining items
GeeWee commentedon Oct 9, 2020
Why doesn't that make sense? I'd certainly expect if I have a background service running that fails at some point and I haven't caught the error, that it would bring the application down.
eerhardt commentedon Oct 9, 2020
anurse was very adamant that a BackgroundService throwing an exception shouldn't bring down the application. See the thread here:
#36017 (comment)
In my opinion, this issue is to make these two scenarios consistent:
Since the 2nd case shouldn't bring down the application, neither should the first case.
GeeWee commentedon Oct 9, 2020
He does seem to be rather adamant about that. I personally think that's the wrong decision (particularly for worker services you can end up in a situation where the entire process just does.. nothing and you don't know unless you have alerts on your logs) - but hey ¯\(ツ)/¯
davidfowl commentedon Oct 9, 2020
Right, I think it's fine to suggest an option on HostOptions that would fail if any background service task throws but it wouldn't be the default.
GeeWee commentedon Oct 13, 2020
Let me try to paint the worst case scenario for each "mode".
Scenario 1. You have a non-important Service and the default is to crash on unhandled errors
This brings your application down. You go look at the logs, and you see that it's your
NotImportantServicethat brought the house down. You curse under your breath, and wrap it in a dummy catch or a Polly retry or whatever. Worst case is you get some downtime once.Scenario 2. You have an important service, and the default is to just let it die
Your service runs some stuff every hour. At some point data stops coming through. You look at the server - it's running fine (and you don't know that a crashing BackgroundService doesn't crash the server). You look at the logs. Finding anything is hard (impossible without this new PR), because the service could have crashed a long time ago. You mutter under your breath, and figure out how to properly close the application via IApplicationLifetime or similar.
I'm not exaggerating when I've seen people spend weeks re-writing stuff because they were unable to debug a silently crashing BackgroundService, and thought the process was gettign OOMKilled or similar.
All I'm saying is that the failure mode for Scenario 2 is much worse, which is why I think that crashing should be the default. Admittedly that calculation was more heavily skewed back when we didn't even have any logs.
But perhaps the right solution is for there to be no default - but forcing the user to explicitly specify "Should this backgroundservice crash the server on an uncaught error" - because I agree that there are both types of services.
Rassi commentedon Jan 18, 2021
I have just been hit by this along with several colleagues. We have a long running background service pulling from a message queue (Google PubSub). The message queue service is started (await StartAsync) and completes only when manually stopped, or when an unrecovereable error occurs. This recently started periodically failing silently for long periods of time until a restart. And it took us a long time to figure out was a permission issue, even though an exception was thrown by StartAsync.
Our assumptions mirrors @GeeWee's thoughts, that an unhandled exception is exceptional, and will result in the application exiting. This has been my logic for many years, stemming from multiple sources (some listed below). If you need something to be resilient against exceptions, then it is an active choice you make, and wrap it in a try..catch. Having code swallow exceptions that are too vague is something that I point out again and again in code reviews, since there is a risk of hiding unknown future errors, and since I expect the runtime to catch any unhandled exceptions.
BackgroundService seems to flip this upside down, and now we have to actively handle unknown exceptions in every BackgroundService we implement.
davidfowl commentedon Jan 18, 2021
See #43637 (comment) for the API proposal.
GeeWee commentedon Jan 19, 2021
I just want to do a shameless plug that I've implemented a tiny library BetterHostedServices that lets you inherit from
CriticalBackgroundServicewhich will end the application on an uncaught exception.Hopefully this issue will get fixed in the core library but until then this is a band-aid solution.
mathmul commentedon Dec 13, 2022
Curious if this is still being worked on. The "Future" tag is rather vague. Having a similar issue as @Rassi, I completely agree with @GeeWee.
lwestfall commentedon Dec 13, 2022
@mathmul it looks like this was fixed in #50569 for .NET 6. I think this issue should be closed? @davidfowl
mathmul commentedon Dec 13, 2022
Thanks. Docs
GeeWee commentedon Dec 14, 2022
Yes I think this has been long-fixed.
buyaa-n commentedon Dec 14, 2022
Closing as per comments above