runtime: Different Exit code when IHost stops from failing (async)IHostedService
Given the following Program.cs
IHost host = Host.CreateDefaultBuilder(args)
.ConfigureServices(services =>
{
services.AddHostedService<Worker>();
services.Configure<HostOptions>(hostOptions =>
{
hostOptions.BackgroundServiceExceptionBehavior = BackgroundServiceExceptionBehavior.StopHost;
});
})
.Build();
await host.RunAsync();
And Worker.cs
public class Worker : BackgroundService
{
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
//await Task.Delay(TimeSpan.FromSeconds(1), stoppingToken);
throw new Exception();
}
}
I get an ‘error’ exit code, which is usefull to detect errors in let’s say kubernetes
Process finished with exit code 134.
However when uncommenting the ‘await Task…’
There is no longer an ‘error’ exit code
crit: Microsoft.Extensions.Hosting.Internal.Host[10]
The HostOptions.BackgroundServiceExceptionBehavior is configured to StopHost. A BackgroundService has thrown an unhandled exception, and the IHost instance is stopping. To avoid this behavior, configure this to Ignore; however the BackgroundService will not be restarted.
System.Exception: Exception of type 'System.Exception' was thrown.
at TestUpgrade.Worker.ExecuteAsync(CancellationToken stoppingToken) in Worker.cs:line 8
at Microsoft.Extensions.Hosting.Internal.Host.TryExecuteBackgroundServiceAsync(BackgroundService backgroundService)
info: Microsoft.Hosting.Lifetime[0]
Application is shutting down...
Process finished with exit code 0. <-------
Is there a way to detect this case using the hostbuilder ?
About this issue
- Original URL
- State: open
- Created 5 years ago
- Reactions: 15
- Comments: 15 (12 by maintainers)
Extension I put together just now for a template we’re working on that ensures the app exits with a non-zero exit code if a
BackgroundServicefaults:Simply call this method instead of
RunAsync()/Run()from yourProgram.Main.Alternative is add an additional
IHostedServicelike the folllowing:Given the impact of the current behavior in environments like Kubernetes, Azure Container Apps, Aspire, etc., I think we should prioritize improving this behavior in the runtime. As @msschl suggest, we should add a new value to
BackgroundServiceExceptionBehavior(e.g.StopHostAndSetExitNonZeroCode, aka my best name suggestion ever) in .NET 10. We should also consider servicing .NET 8 and .NET 9 to enable this behavior via an app context switch (i.e. quirk it) so that folks can get the benefit of this change without having to wait for .NET 10.Exiting due to failure with a success exit code is bad.
This seems like the proper thing to do.
StopAsyncalready throws anAggregateExceptionwhenIHostedServicesthrow duringStopAsync.We can’t capture the exception for the generic
IHostedServicesbecause they don’t have aTaskthat tracks the execution. It is possible forBackgroundService, which has such aTask(ExecuteTaskproperty). (note:ExecuteTaskisn’t set if someone overrides StartAsync but forgets to call the base version.)