Skip to content

Different Exit code when IHost stops from failing (async)IHostedService #67146

@Vandersteen

Description

@Vandersteen

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 ?

Metadata

Metadata

Assignees

Labels

area-Extensions-Hostingbugin-prThere is an active PR which will close this issue when it is merged

Type

No type

Projects

No projects

Relationships

None yet

Development

No branches or pull requests

Issue actions