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)

Most upvoted comments

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 BackgroundService faults:

public static class HostExtensions
{
    public static async Task RunAndObserveBackgroundServices(this IHost host)
    {
        var backgroundServiceTasks = host.Services.GetServices<IHostedService>()
            .OfType<BackgroundService>().Select(s => s.ExecuteTask);

        await host.RunAsync();

        if (backgroundServiceTasks.Any(t => t?.IsFaulted == true))
        {
            // If a BackgroundService failed, set the exit code to -1.
            Environment.ExitCode = -1;
        }
    }
}

Simply call this method instead of RunAsync()/Run() from your Program.Main.

Alternative is add an additional IHostedService like the folllowing:

class BackgroundServiceObserver(IServiceProvider serviceProvider) : IHostedService
{
    public Task StartAsync(CancellationToken cancellationToken) => Task.CompletedTask;

    public Task StopAsync(CancellationToken cancellationToken)
    {
        var backgroundServiceTasks = serviceProvider.GetServices<IHostedService>()
            .OfType<BackgroundService>().Select(s => s.ExecuteTask);

        if (backgroundServiceTasks.Any(t => t?.IsFaulted == true))
        {
            // If a BackgroundService failed, set the exit code to -1.
            Environment.ExitCode = -1;
        }

        return Task.CompletedTask;
    }
}

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.

We can store the exception and make StopAsync throw observe the exception.

This seems like the proper thing to do. StopAsync already throws an AggregateException when IHostedServices throw during StopAsync.

We can’t capture the exception for the generic IHostedServices because they don’t have a Task that tracks the execution. It is possible for BackgroundService, which has such a Task (ExecuteTask property). (note: ExecuteTask isn’t set if someone overrides StartAsync but forgets to call the base version.)