System.Threading.Channels

Many background queue implementations still rely on BlockingCollection<T>. While simple, it relies on synchronous OS monitor primitives that block worker threads when empty or full.

System.Threading.Channels provides an asynchronous, lock-free alternative designed for high-throughput producer/consumer pipelines.

Before: BlockingCollection

var queue = new BlockingCollection<WorkItem>(boundedCapacity: 1000); // Blocks thread pool thread if full queue.Add(item); // Synchronously blocks thread if empty var work = queue.Take(); 

After: Bounded Async Channel

var options = new BoundedChannelOptions(1000) { FullMode = BoundedChannelFullMode.Wait, SingleReader = true, SingleWriter = false }; var channel = Channel.CreateBounded<WorkItem>(options); // Asynchronously yields without blocking thread pool await channel.Writer.WriteAsync(item, ct); await foreach (var work in channel.Reader.ReadAllAsync(ct)) { await ProcessAsync(work, ct); } 

Why It Matters

  • No Thread Starvation: Awaiting ReadAsync or ReadAllAsync suspends the state machine instead of holding an active thread pool thread captive.
  • Optimized Concurrency: Setting SingleReader = true or SingleWriter = true enables lock-free single-producer/single-consumer ring buffer paths.
  • Zero-Allocation Reads: Returns ValueTask<T>, eliminating heap allocations when items are immediately ready.

Watch out: You must explicitly invoke channel.Writer.Complete() or channel.Writer.TryComplete(ex) on shutdown; otherwise ReadAllAsync() never terminates.

Have you transitioned your BackgroundService queues to Channels yet?