Recipe 14.4 · C#
In-Process Queues With System.Threading.Channels
Problem
A web request needs to start work that takes longer than the user should wait: sending a receipt e-mail, generating a PDF, calling a slow partner. You want to return immediately and do the work in the background, with a limit on how much can pile up and a fixed number of workers.
The way it's often written
Anti-pattern: shown so you can recognize it. Don't copy this one.
// Not to copy: unbounded, unobserved, dies with the request scope
public IActionResult Checkout(Order order)
{
_orders.Save(order);
Task.Run(() => _email.SendReceipt(order.Id)); // fire and forget
return RedirectToAction("Thanks");
}
Task.Run from a request has no limit: a burst of orders starts a burst of concurrent sends. If
_email is scoped to the request, it may be disposed before the task runs. Exceptions are lost.
And at shutdown, the host doesn't know the tasks exist, so it stops without waiting for them.
The improved recipe
A bounded Channel<T> is the queue, a hosted service runs a fixed number of consumers, and each
item is handled in its own scope.
using System.Threading;
using System.Threading.Channels;
using System.Threading.Tasks;
namespace ImproveCode.Jobs;
public interface IQueueHandler<in T>
{
Task HandleAsync(T item, CancellationToken ct);
}
public sealed class BackgroundQueue<T>
{
private readonly Channel<T> _channel;
public BackgroundQueue(int capacity)
{
_channel = Channel.CreateBounded<T>(
new BoundedChannelOptions(capacity)
{
FullMode = BoundedChannelFullMode.Wait,
});
}
public ChannelReader<T> Reader => _channel.Reader;
public int Count => _channel.Reader.Count;
/// <summary>Waits while the queue is full.</summary>
public ValueTask EnqueueAsync(T item, CancellationToken ct = default) =>
_channel.Writer.WriteAsync(item, ct);
/// <summary>Returns false at once if the queue is full.</summary>
public bool TryEnqueue(T item) => _channel.Writer.TryWrite(item);
public void Complete() => _channel.Writer.TryComplete();
}
using System;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
namespace ImproveCode.Jobs;
public sealed class QueueWorkerService<T>(
BackgroundQueue<T> queue,
IServiceScopeFactory scopes,
ILogger<QueueWorkerService<T>> logger,
int workerCount) : BackgroundService
{
protected override Task ExecuteAsync(
CancellationToken stoppingToken) =>
Task.WhenAll(Enumerable.Range(1, workerCount)
.Select(_ => WorkAsync(stoppingToken)));
public override async Task StopAsync(
CancellationToken cancellationToken)
{
// Stop accepting work, then let the workers drain the queue
// until the host's shutdown timeout runs out.
queue.Complete();
if (ExecuteTask is not null)
{
await Task.WhenAny(ExecuteTask,
Task.Delay(Timeout.Infinite, cancellationToken));
}
await base.StopAsync(cancellationToken);
}
private async Task WorkAsync(CancellationToken stoppingToken)
{
await foreach (T item in queue.Reader.ReadAllAsync())
{
if (stoppingToken.IsCancellationRequested)
{
logger.LogWarning(
"Shutdown timeout: {Count} queued items abandoned",
queue.Count + 1);
return;
}
try
{
await using AsyncServiceScope scope =
scopes.CreateAsyncScope();
await scope.ServiceProvider
.GetRequiredService<IQueueHandler<T>>()
.HandleAsync(item, stoppingToken);
}
catch (Exception ex)
{
logger.LogError(ex, "Failed to handle {Item}", item);
}
}
}
}
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
namespace ImproveCode.Jobs;
public static class BackgroundQueueServiceCollectionExtensions
{
public static IServiceCollection AddBackgroundQueue<T, THandler>(
this IServiceCollection services,
int capacity = 1000,
int workers = 1)
where THandler : class, IQueueHandler<T>
{
services.AddSingleton(new BackgroundQueue<T>(capacity));
services.AddScoped<IQueueHandler<T>, THandler>();
services.AddHostedService(sp => new QueueWorkerService<T>(
sp.GetRequiredService<BackgroundQueue<T>>(),
sp.GetRequiredService<IServiceScopeFactory>(),
sp.GetRequiredService<ILogger<QueueWorkerService<T>>>(),
workers));
return services;
}
}
Usage in an ASP.NET Core app, with a small message record and a handler that sends the e-mail (Chapter 9 covers the sending):
builder.Services.AddBackgroundQueue<SendReceipt, SendReceiptHandler>(
capacity: 500, workers: 4);
app.MapPost("/orders/{id:int}/receipt",
async (int id, BackgroundQueue<SendReceipt> queue,
CancellationToken ct) =>
{
await queue.EnqueueAsync(new SendReceipt(id), ct);
return Results.Accepted();
});
How it works
A channel is a thread-safe producer-consumer queue built for async code. WriteAsync adds an
item, and ReadAllAsync yields items as they arrive, waiting without blocking a thread when the
queue is empty. Many producers and many consumers can use it at once.
The capacity is the important design choice. With BoundedChannelFullMode.Wait, a full queue
makes EnqueueAsync wait until a worker frees a slot. That is backpressure: under a burst, callers
slow down instead of the process filling memory with a million pending items. When a caller
should never wait, such as a request handler with a strict latency budget, use TryEnqueue and
return 503 Service Unavailable when it returns false.
QueueWorkerService starts workerCount loops that read from the same channel, so at most that
many items are handled at once. Each item gets its own scope, which gives the handler fresh scoped
services, unlike the request-scoped services that Task.Run captured.
Shutdown is ordered. StopAsync completes the writer first, so no new items are accepted. The
workers keep reading until the queue is empty, at which point ReadAllAsync ends and so does
ExecuteAsync. Only if the host's shutdown timeout runs out first is the stoppingToken
cancelled, the in-flight handlers told to stop, and the remainder logged as abandoned.
I tested the queue with a capacity of 10, four workers and 1,000 items from two producers: all
1,000 were handled exactly once, and items still queued when the host was stopped were drained
before StopAsync returned.
Variations and pitfalls
- The queue lives in memory. If the process crashes or the server reboots, queued items are gone. For anything that must not be lost, such as payments or regulatory filings, write the work to a database table or a durable broker first, and use the channel only to wake a worker. Or use Hangfire (Recipe 14.6).
- One queue per message type.
BackgroundQueue<SendReceipt>andBackgroundQueue<BuildPdf>are separate singletons with separate capacities and worker counts. Slow PDFs then cannot starve e-mail. - Retries. A handler that fails is logged and dropped. Add a retry with backoff inside the handler (Chapter 5), or re-enqueue with an attempt counter on the message record.
- Unbounded channels.
Channel.CreateUnbounded<T>()is fine when the producer is naturally limited, such as a file watcher. For anything driven by user traffic, always set a bound.