skip to content

How do you consume a System.Threading.Channels queue with limited concurrency in an ASP.NET Core BackgroundService, and which ChannelOptions settings matter?

level: middleimportance: should knowfreq 28%

answer

  1. N readers, one shared channel
  2. each item goes to one reader
  3. SingleReader stays false
  4. AllowSynchronousContinuations stays false
  5. capacity bounds memory, readers bound CPU

basics

~20 s

Start a fixed number of reader loops over the same ChannelReader and await them together; each item goes to exactly one reader. Keep SingleReader false with several readers and AllowSynchronousContinuations false so writers never run consumer code.

solid answer

~40 s

Inside `ExecuteAsync`, start N loops that each run `await foreach (var job in reader.ReadAllAsync(stoppingToken))`, and `await Task.WhenAll(...)` them. The channel hands each item to exactly one waiting reader, so N is the concurrency limit, while the bounded capacity limits memory. The relevant `ChannelOptions`: `SingleReader` must stay `false` (its default) when several loops read, because `true` promises at most one read operation at a time and lets the channel pick an implementation that relies on it. `SingleWriter` must stay `false` when many requests write concurrently. `AllowSynchronousContinuations` should stay `false`, otherwise a request's write may run a waiting reader's continuation inline on the request thread. Items leave the queue in order but finish out of order, and each job still gets its own DI scope.

code

csharp · 23 lines
csharp
public sealed class ThumbnailWorker(
    ChannelReader<ThumbnailJob> jobs,
    IServiceScopeFactory scopeFactory,
    ILogger<ThumbnailWorker> logger) : BackgroundService
{
    private const int Readers = 4;
    protected override Task ExecuteAsync(CancellationToken stoppingToken) =>
        Task.WhenAll(Enumerable.Range(0, Readers).Select(_ => ConsumeAsync(stoppingToken)));

    private async Task ConsumeAsync(CancellationToken ct)
    {
        await foreach (var job in jobs.ReadAllAsync(ct))
        {
            try
            {
                await using var scope = scopeFactory.CreateAsyncScope();
                await scope.ServiceProvider.GetRequiredService<ThumbnailRenderer>().RenderAsync(job.PhotoId, ct);
            }
            catch (Exception ex) when (ex is not OperationCanceledException)
            { logger.LogError(ex, "Rendering failed for {PhotoId}", job.PhotoId); }
        }
    }
}

go deeper

for a junior

Recall that several loops can read the same channel and that each item is handed to only one of them.

for a middle

Explain how to start N readers under one ExecuteAsync, why each needs its own scope, and what SingleReader, SingleWriter and AllowSynchronousContinuations promise.

for a senior

Size readers and capacity from the resource the work consumes, keep one reader's failure from ending the others, and account for out-of-order completion.

for a principal

Judge when in-process parallel consumers stop scaling and the work should move to separate worker processes fed by a shared durable queue.

## Why one reader may not be enough A single `await foreach` loop processes one thumbnail job at a time. If rendering takes two seconds and uploads arrive at three per second, the queue fills no matter how large it is. Rendering on four cores at once would keep up. The channel itself supports that directly: several readers can wait on one `ChannelReader<T>`, and each item is delivered to **exactly one** of them. ## The pattern 1. Choose N from the resource the work consumes: cores for CPU-bound rendering, the external service's limit for I/O. 2. In `ExecuteAsync`, start N copies of the same consumer loop. 3. `await Task.WhenAll(...)` so `ExecuteAsync` represents all of them; the host's error handling and shutdown wait then cover every loop. 4. Give each job its own scope with `IServiceScopeFactory.CreateAsyncScope()`, because the readers run concurrently and a `DbContext` must not be shared between them. 5. Catch per job inside each loop so one failure does not end that reader. When the writer completes, or `stoppingToken` is cancelled, every reader's `ReadAllAsync` ends and `Task.WhenAll` completes. ## The options that matter All channel options classes inherit three flags from `ChannelOptions`, each `false` by default: | Option | Meaning when `true` | For this design | |---|---|---| | `SingleReader` | readers guarantee at most one read operation at a time | keep `false`: several loops read concurrently | | `SingleWriter` | writers guarantee at most one write operation at a time | keep `false`: many requests write concurrently | | `AllowSynchronousContinuations` | operations may run waiting continuations synchronously | keep `false`: a request's write should not execute consumer code | `SingleReader = true` is a **promise**, not a preference. For an unbounded channel it selects an implementation built for a single consumer; breaking the promise with several readers is unsupported. Use it only when exactly one loop reads. `AllowSynchronousContinuations = true` can save a thread hop, but on a channel written by endpoints it means a `TryWrite` call may continue a waiting reader on the request's own thread, so request latency starts to include rendering work. ## Ordering and fairness - Items are **dequeued** in FIFO order, but with N readers they **complete** in any order: a small photo started second can finish first. - No reader owns particular items; whichever reader is waiting takes the next one. - If certain jobs must run in sequence relative to each other, N readers on one channel does not provide it. ## Mistakes that look like concurrency - Starting a `Task.Run` per item inside a single reader loop: concurrency is now unbounded again, and the loop no longer waits for anything. - Returning from `ExecuteAsync` after starting the readers: the host stops watching them. - Resolving one scoped service outside the loops and sharing it across readers. ## Capacity and readers together - **Readers** bound concurrency: CPU, connections, calls to a rate-limited API. - **Capacity** bounds memory and worst-case wait. - Throughput is roughly N divided by the per-job time; capacity divided by throughput is how long the last queued job waits. All of it is per process: three replicas run three channels and 3 x N readers, each draining only its own queue.

  • Why await Task.WhenAll of the reader loops instead of starting them and returning from ExecuteAsync?
    The task `ExecuteAsync` returns is what the host watches. Awaiting `Task.WhenAll` makes a reader's crash fault that task, so the host logs it and applies `BackgroundServiceExceptionBehavior`, and `StopAsync` waits for all readers at shutdown. Loops started and forgotten are invisible to both.
  • When is setting SingleReader = true on the channel correct?
    When exactly one loop ever reads, as in the classic single-consumer worker. Then the channel can use an implementation optimised for one reader, which is a small gain. With several readers the flag must stay false, because the single-reader implementation assumes at most one read operation at a time.

  • With four readers, every reader receives every item
  • Set SingleReader = true to make several readers faster
  • AllowSynchronousContinuations = true makes writes from endpoints safer
  • Several readers on one channel still complete jobs in FIFO order
  • One DbContext can be shared by all reader loops