Unhandled exceptions from a BackgroundService

In previous versions, when a BackgroundService throws an unhandled exception, the exception is lost and the service appears unresponsive. .NET 6 fixes this behavior by logging the exception and stopping the host.

Change description

In previous .NET versions, when an exception is thrown from a BackgroundService.ExecuteAsync(CancellationToken) override, the exception is lost and the service appears unresponsive. The host continues to run, and no message is logged.

Starting in .NET 6, when an exception is thrown from a BackgroundService.ExecuteAsync(CancellationToken) override, the exception is logged to the current ILogger. By default, the host is stopped when an unhandled exception is encountered.

Version introduced

.NET 6

Reason for change

The new behavior is consistent with the way other app models behave when unhandled exceptions are encountered. It's also confusing to developers when their BackgroundService encounters an error, but nothing is logged. The best default behavior is to stop the host, because unhandled exceptions shouldn't be ignored. They indicate a problem that needs attention.

If you prefer to keep the previous behavior of allowing an unhandled exception in a BackgroundService to not stop the Host, you can set HostOptions.BackgroundServiceExceptionBehavior to BackgroundServiceExceptionBehavior.Ignore.

Host.CreateBuilder(args)
    .ConfigureServices(services =>
    {
        services.Configure<HostOptions>(hostOptions =>
        {
            hostOptions.BackgroundServiceExceptionBehavior = BackgroundServiceExceptionBehavior.Ignore;
        });
    });

Affected APIs