Background workers are responsible for many important operations in modern .NET applications. They process queued messages, send notifications, generate reports, synchronize data, execute scheduled tasks, and communicate with external services.
These workers often run continuously using BackgroundService. However, a deployment, container restart, application update, or infrastructure change can stop the application while a worker is processing a job.
If the worker does not handle shutdown correctly, several problems can occur. A database operation may be interrupted, a message may be lost, an external API request may be submitted twice, or a partially completed job may remain in an inconsistent state.
This is why graceful shutdown is an important part of building production-ready background services.
A graceful shutdown gives the worker an opportunity to stop accepting new work, complete or safely interrupt its current operation, release resources, and exit within the available shutdown time.
This article explains how .NET workers respond to deployment shutdown signals, how to use cancellation tokens correctly, and how to design long-running jobs that can recover safely when the application stops.
Understanding What Happens During Application Shutdown
A .NET application normally runs under a hosting environment that manages its startup and shutdown lifecycle.
When the application receives a graceful shutdown request, the Generic Host begins stopping its hosted services. BackgroundService receives a cancellation request through the token passed to ExecuteAsync.
The worker should observe this token and stop its ongoing operations.
For example, when a container is stopped, the container runtime can send a termination signal to the application process. In Kubernetes, the container's main process normally receives SIGTERM when its Pod is terminated. The application is given a termination grace period to shut down before Kubernetes forcefully terminates it.
A simplified shutdown sequence looks like this:
Deployment starts
|
v
Old application receives shutdown signal
|
v
.NET Generic Host begins shutdown
|
v
BackgroundService receives cancellation
|
v
Worker stops accepting new jobs
|
v
Current operation completes or is safely interrupted
|
v
Resources are released
|
v
Application process exitsThe important part is that the worker must cooperate with the shutdown process. The host cannot safely finish an operation if the worker ignores cancellation or blocks indefinitely.
Also, graceful shutdown is not guaranteed in every situation. A process crash, machine failure, forced termination, or SIGKILL can prevent the application from completing its shutdown logic.
Therefore, graceful shutdown should be combined with durable job processing and recovery mechanisms.
Use the Cancellation Token in BackgroundService
The most important part of graceful shutdown is the CancellationToken supplied to ExecuteAsync.
Consider a worker that processes pending orders:
public sealed class OrderWorker : BackgroundService
{
private readonly ILogger<OrderWorker> _logger;
public OrderWorker(
ILogger<OrderWorker> logger)
{
_logger = logger;
}
protected override async Task ExecuteAsync(
CancellationToken stoppingToken)
{
_logger.LogInformation(
"Order worker started");
while (!stoppingToken.IsCancellationRequested)
{
try
{
await ProcessPendingOrdersAsync(
stoppingToken);
}
catch (OperationCanceledException)
when (stoppingToken.IsCancellationRequested)
{
_logger.LogInformation(
"Order processing cancelled during shutdown");
break;
}
catch (Exception ex)
{
_logger.LogError(
ex,
"Error while processing orders");
}
}
_logger.LogInformation(
"Order worker stopped");
}
private static async Task ProcessPendingOrdersAsync(
CancellationToken cancellationToken)
{
await Task.Delay(
TimeSpan.FromSeconds(10),
cancellationToken);
}
}When the host begins shutdown, stoppingToken is cancelled. The worker's delay observes that cancellation and exits instead of waiting for the complete ten seconds.
This is better than using Task.Delay without a cancellation token because an uncancellable delay can keep the worker alive unnecessarily.
The same token should be passed to database operations, HTTP requests, message consumers, and other asynchronous operations whenever those APIs support cancellation.
For example:
await dbContext.SaveChangesAsync(cancellationToken);
await httpClient.SendAsync(
request,
cancellationToken);A common mistake is to check stoppingToken only at the beginning of the loop. If the worker then performs a long-running operation without passing the token to that operation, shutdown may still be delayed.
Cancellation must be supported throughout the complete execution path.
Stop Accepting New Work Before Shutting Down
A production worker should distinguish between accepting new work and completing work that has already started.
Suppose a worker reads messages from a queue. When shutdown begins, it should stop requesting new messages. However, it may still need to finish processing the message it has already received.
A simplified example is shown below:
public sealed class QueueWorker : BackgroundService
{
private readonly IMessageProcessor _processor;
private readonly ILogger<QueueWorker> _logger;
public QueueWorker(
IMessageProcessor processor,
ILogger<QueueWorker> logger)
{
_processor = processor;
_logger = logger;
}
protected override async Task ExecuteAsync(
CancellationToken stoppingToken)
{
_logger.LogInformation(
"Queue worker started");
while (!stoppingToken.IsCancellationRequested)
{
var message = await _processor.ReceiveAsync(
stoppingToken);
if (message is null)
{
continue;
}
try
{
await _processor.ProcessAsync(
message,
stoppingToken);
await _processor.CompleteAsync(
message,
stoppingToken);
}
catch (OperationCanceledException)
when (stoppingToken.IsCancellationRequested)
{
_logger.LogInformation(
"Shutdown requested while processing a message");
break;
}
}
_logger.LogInformation(
"Queue worker stopped");
}
}This example illustrates the basic flow, but the exact behavior depends on the message broker and its acknowledgment model.
If processing is cancelled before completion, the worker should not acknowledge the message as successfully processed. The message should remain available for redelivery or become available again after its visibility timeout or delivery lease expires.
If the message has already been acknowledged, the application may lose the opportunity to retry it after a crash.
For this reason, acknowledge messages only after the required business operation has completed successfully.
Also, avoid treating every cancellation as an error. Cancellation caused by an expected shutdown request is a normal part of the application lifecycle.
Handle Long Running Operations Safely
Some jobs take several minutes or even hours to complete. Examples include generating large reports, importing files, processing videos, and synchronizing large datasets.
Trying to finish every operation during shutdown may not be realistic.
Instead, divide long-running work into smaller units that can be completed independently.
For example, instead of processing an entire file in one operation, process it in batches.
public async Task ProcessFileAsync(
string filePath,
CancellationToken cancellationToken)
{
const int batchSize = 500;
var offset = 0;
while (true)
{
cancellationToken.ThrowIfCancellationRequested();
var records = await ReadBatchAsync(
filePath,
offset,
batchSize,
cancellationToken);
if (records.Count == 0)
{
break;
}
await ProcessBatchAsync(
records,
cancellationToken);
await SaveCheckpointAsync(
offset + records.Count,
cancellationToken);
offset += records.Count;
}
}The example saves a checkpoint after each successfully processed batch.
If the application stops, the next worker instance can use the checkpoint to continue from the last completed batch instead of starting from the beginning.
Join the conversation! Your thoughts help the community grow.