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
When awaiting an async method from ExecuteAsync which throws an unhandled exception, the service hangs #36017
In a .Net Core Worker Service, whenever an exception is thrown inside an async method, and you happened to not surround the method invocation in a try/catch, the application will simply hang when it hits the exception -- giving no sign that an exception has occured at all.
The same code applied within a simple Console Application does indeed work as expected, and you get the normal "unhandled exception" behaviour.
A background service throwing an error during ExecuteAsync doesn't cause the app to shut down. That's intentional behavior. If you want that behavior, you'll have to try..catch and use the IApplicationLifetime.
giving no sign that an exception has occured at all.
We could consider logging the exception as it occurs (today it should be logged or manifested somehow when the host stops).
As you can see, any exception thrown synchronously will crash the service (which is what I'd expect). However, when thrown in combination with some asynchronous operation it will just silently hang.
I feel the behaviour should have been consistent in all of these cases.
We should really make sure that these exceptions are at least logged. I've been helping @stevejgordon with putting together some worker samples, and it's a painful lesson that everyone using worker seems to have to learn once.
In general if the framework is calling user-code we should make sure the exception is at least logged - I think there's a bigger discussion to be had about whether an unhandled exception from an IHostedService should be treated as a crash - or maybe that should be shown in docs. I say these things from the point of view of "we provide a template that gives you a single background service" - and if you crash out from that service you have no way of knowing.
Reacted by Dylan Reisenberger, Steve Gordon, rcollina, Lukas Kolletzki, MoonStorm, Dmytro Pryvedeniuk and Gustav Wengel
This is a reasonable candidate for 5.0, but it'll be up to the runtime team to prioritize for sure :). The idea here would be to have BackgroundService.StartAsync set up the call to ExecuteAsync so that any exceptions thrown by it are logged and then rethrown.
I investigated this issue and here is what I found:
There is a problem that there is no good location to do the logging. When the ExecutingTask is not finished in StartAsync, the BackgroundService class holds privately on to the returned ExecutingTask.
// If the task is completed then return it, this will bubble cancellation and failure to the caller
if(_executingTask.IsCompleted)
{
return_executingTask;
}
// Otherwise it's running
returnTask.CompletedTask;
}
We could add a .ContinueWith on the _executingTask and check if an exception was thrown. However, there is nothing we can do in BackgroundService because it doesn't contain a Logger of any kind. so that's a dead end.
The more correct place for the logging to occur would be in the Host that starts the task. The Host already contains a logger, so it can simply log any exception to it:
However, the Host doesn't have access to the _executingTask, since BackgroundService doesn't expose it, and the Task returned from hostedService.StartAsync is the CompletedTask returned from BackgroundService.StartAsync above. So the Host has no way of knowing anything about the ExecutingTask.
We could do some hack to make this work in 5.0, but the real fix would be to expose the ExecutingTask on BackgroundService. This has come up before: #35991. So we will need to wait for that - which will need to go through API approval, which won't happen until 6.0.
if (_executingTask.IsCompleted)
{
return _executingTask;
}
The _executingTask might fail immediately after this check. The check is probabilistic. It does not reliably address the case that the _executingTask failed. But it does add an additional case to the logic which alters behavior just sometimes. If this check is removed, nothing functional is lost but behavior becomes more uniform.
Activity
analogrelay commentedon Dec 6, 2019
A background service throwing an error during ExecuteAsync doesn't cause the app to shut down. That's intentional behavior. If you want that behavior, you'll have to
try..catchand use theIApplicationLifetime.We could consider logging the exception as it occurs (today it should be logged or manifested somehow when the host stops).
Tratcher commentedon Dec 6, 2019
Which caller? Program.Main?
hognevevle commentedon Dec 8, 2019
@Tratcher Good question, for which I don't have the answer.
This screen recording might help clarify the issue at hand: https://drive.google.com/file/d/1gdMzXwQi2VzWP1OUivYgiY-yyDELpDGB/view
As you can see, any exception thrown synchronously will crash the service (which is what I'd expect). However, when thrown in combination with some asynchronous operation it will just silently hang.
I feel the behaviour should have been consistent in all of these cases.
analogrelay commentedon Dec 11, 2019
This is because
StartAsyncis set up to return the faulted task immediately if it's already faulted by the time it's returned byExecuteAsync. It's likely this would be resolved by https://github.com/aspnet/Extensions/issues/2149This is behavior I'd expect. In general, BackgroundServices do not crash the process when they fail by design.
rynowak commentedon Feb 7, 2020
We should really make sure that these exceptions are at least logged. I've been helping @stevejgordon with putting together some worker samples, and it's a painful lesson that everyone using worker seems to have to learn once.
In general if the framework is calling user-code we should make sure the exception is at least logged - I think there's a bigger discussion to be had about whether an unhandled exception from an
IHostedServiceshould be treated as a crash - or maybe that should be shown in docs. I say these things from the point of view of "we provide a template that gives you a single background service" - and if you crash out from that service you have no way of knowing.analogrelay commentedon May 7, 2020
This is a reasonable candidate for 5.0, but it'll be up to the runtime team to prioritize for sure :). The idea here would be to have
BackgroundService.StartAsyncset up the call toExecuteAsyncso that any exceptions thrown by it are logged and then rethrown.Dotnet-GitSync-Bot commentedon May 7, 2020
I couldn't figure out the best area label to add to this issue. Please help me learn by adding exactly one area label.
eerhardt commentedon Aug 20, 2020
I investigated this issue and here is what I found:
There is a problem that there is no good location to do the logging. When the
ExecutingTaskis not finished inStartAsync, theBackgroundServiceclass holds privately on to the returnedExecutingTask.runtime/src/libraries/Microsoft.Extensions.Hosting.Abstractions/src/BackgroundService.cs
Lines 13 to 15 in a52f237
And in
StartAsync, it returnsTask.CompletedTasksaying that the service is done starting:runtime/src/libraries/Microsoft.Extensions.Hosting.Abstractions/src/BackgroundService.cs
Lines 30 to 46 in a52f237
We could add a
.ContinueWithon the_executingTaskand check if an exception was thrown. However, there is nothing we can do inBackgroundServicebecause it doesn't contain a Logger of any kind. so that's a dead end.The more correct place for the logging to occur would be in the Host that starts the task. The Host already contains a logger, so it can simply log any exception to it:
runtime/src/libraries/Microsoft.Extensions.Hosting/src/Internal/Host.cs
Lines 51 to 55 in a52f237
However, the Host doesn't have access to the
_executingTask, sinceBackgroundServicedoesn't expose it, and the Task returned fromhostedService.StartAsyncis the CompletedTask returned fromBackgroundService.StartAsyncabove. So the Host has no way of knowing anything about the ExecutingTask.We could do some hack to make this work in
5.0, but the real fix would be to expose theExecutingTaskonBackgroundService. This has come up before: #35991. So we will need to wait for that - which will need to go through API approval, which won't happen until 6.0.GSPP commentedon Aug 21, 2020
The
_executingTaskmight fail immediately after this check. The check is probabilistic. It does not reliably address the case that the_executingTaskfailed. But it does add an additional case to the logic which alters behavior just sometimes. If this check is removed, nothing functional is lost but behavior becomes more uniform.Expose BackgroundService.ExecuteTask
Expose BackgroundService.ExecuteTask (#42981)