Developer knowledge network · moderated exchange

Zajednica UnreliableCode

Zajednica za istraživanje, obrnuti inženjering i programiranje programera

Knowledge indexŽivjeti
4Categories
919Threads
2.8KPostovi
Tutorial

Proper Exception Handling and Graceful Shutdown in BackgroundService and IHostedService [StackOverflow Architecture Guide]

csharp_async_master
Async & Task Expert
MEMBER
Rep: 57
Datum pridruživanja: Mar 2019
Postovi: 18
Hvala: 40
prije 1 mjeseci · Jul 2, 2026 10:07 PM
#1

Why unhandled exceptions inside BackgroundService.ExecuteAsync crash the entire .NET application by default:

In .NET 6+, HostOptions.BackgroundServiceExceptionBehavior defaults to StopHost, shutting down your API server if a background timer throws an unhandled exception.

Robust Background Service Pattern:

CSHARP
public class IngestionWorker : BackgroundService
{
    protected override async Task ExecuteAsync(CancellationToken stoppingToken)
    {
        while (!stoppingToken.IsCancellationRequested)
        {
            try
            {
                await ProcessWorkQueueAsync(stoppingToken);
            }
            catch (OperationCanceledException) when (stoppingToken.IsCancellationRequested)
            {
                // Normal graceful shutdown, exit loop
                break;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Error processing background batch. Retrying in 5s...");
                await Task.Delay(5000, stoppingToken);
            }
        }
    }
}
channel_concurrency
Reactive & Pipeline
MEMBER
Rep: 156
Datum pridruživanja: Jan 2022
Postovi: 10
Hvala: 16
prije 1 mjeseci · Jul 3, 2026 2:00 AM
#2

Catching OperationCanceledException when stoppingToken.IsCancellationRequested is true ensures clean host shutdown without polluting error logs.

dotnet_runtime_architect
.NET Core Specialist
MEMBER
Rep: 103
Datum pridruživanja: Apr 2018
Postovi: 40
Hvala: 24
prije 1 mjeseci · Jul 3, 2026 11:11 AM
#3

Critical template for writing reliable background worker services.