ASP.NET Core Interview Question #168

What happens if a BackgroundService throws an unhandled exception?

Logging, Error Handling & Background Services Mid-Level Intermediate

Quick Interview Answer

An unhandled exception escaping a background service is a serious application failure. Host behavior is configurable, but modern .NET hosting commonly treats an unhandled BackgroundService exception as a reason to stop the host rather than silently leaving the application running without an expected worker.

Detailed Explanation

An unhandled exception escaping a background service is a serious application failure. Host behavior is configurable, but modern .NET hosting commonly treats an unhandled BackgroundService exception as a reason to stop the host rather than silently leaving the application running without an expected worker.

Expected transient failures should therefore be handled inside the worker with appropriate logging and a deliberate retry or recovery policy. Fatal or invariant-breaking failures should not simply be swallowed.

The correct strategy depends on whether the operation can safely retry and whether continuing the application without that worker is acceptable.

Code Example

protected override async Task ExecuteAsync(
    CancellationToken stoppingToken)
{
    while (!stoppingToken.IsCancellationRequested)
    {
        try
        {
            await ProcessAsync(stoppingToken);
        }
        catch (TransientServiceException ex)
        {
            _logger.LogWarning(ex, "Transient worker failure");
            await Task.Delay(5000, stoppingToken);
        }
    }
}