Developer knowledge network · moderated exchange

UnreliableCode 커뮤니티

개발자 연구, 리버스 엔지니어링 및 코딩 커뮤니티

Knowledge index살다
4Categories
919Threads
2.8K게시물
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.