ASP.NET Core › Background Tasks & Hosted Services
How would you implement a producer-consumer background processing pipeline using System.Threading.Channels alongside a BackgroundService?
AdvancedAnswer
Channel<T> provides a high-performance, thread-safe async queue -- a producer (like an API endpoint) writes items via ChannelWriter.WriteAsync, while a BackgroundService acts as the consumer, reading items via ChannelReader.ReadAllAsync in a loop, decoupling request-handling latency from background processing time while a bounded channel provides built-in backpressure if the queue fills up.
var channel = Channel.CreateBounded<EmailMessage>(capacity: 100);
builder.Services.AddSingleton(channel.Writer);
builder.Services.AddSingleton(channel.Reader);
builder.Services.AddHostedService<EmailSenderService>();
public class EmailSenderService : BackgroundService {
protected override async Task ExecuteAsync(CancellationToken ct) {
await foreach (var message in _reader.ReadAllAsync(ct)) {
await SendEmailAsync(message);
}
}
}Real-world example An API endpoint accepting bulk email requests writes each email to a bounded Channel and returns immediately (202 Accepted), while a background service consumes and actually sends the emails, keeping the API responsive under heavy load.