Developer knowledge network ยท moderated exchange

UnreliableCode Community

Developer Research, Reverse Engineering & Coding Community

Knowledge indexLive
4Categories
919Threads
2.8KPosts
Tutorial

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

csharp_async_master
Async & Task Expert
MEMBER
Rep: 57
Join Date: Mar 2019
Posts: 18
Thanks: 40
1 months ago ยท 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
Join Date: Jan 2022
Posts: 10
Thanks: 16
1 months ago ยท 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
Join Date: Apr 2018
Posts: 40
Thanks: 24
1 months ago ยท Jul 3, 2026 11:11 AM
#3

Critical template for writing reliable background worker services.