Developer knowledge network · moderated exchange

UnreliableCode コミュニティ

開発者リサーチ、リバース エンジニアリング、コーディング コミュニティ

Tutorial

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

csharp_async_master
Async & Task Expert
MEMBER
担当者: 57
参加日: Mar 2019
投稿: 18
ありがとう: 40
1 か月前 · 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
担当者: 156
参加日: Jan 2022
投稿: 10
ありがとう: 16
1 か月前 · 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
担当者: 103
参加日: Apr 2018
投稿: 40
ありがとう: 24
1 か月前 · Jul 3, 2026 11:11 AM
#3

Critical template for writing reliable background worker services.