Implement a bounded producer-consumer queue using System.Threading.Channels
cs-sen-002
Your answer
Answer as you would in a real interview — explain your thinking, not just the conclusion.
Model answer
System.Threading.Channels provides an allocation-efficient, first-class alternative to BlockingCollection<T>. I create a BoundedChannel<T> with a defined capacity so producers back-pressure when consumers are lagging. The producer writes via channel.Writer.WriteAsync (or TryWrite for fire-and-forget). The consumer uses await foreach over channel.Reader.ReadAllAsync, which handles cancellation and completion propagation cleanly. Channels are safe for multiple producers and consumers without external locks. I prefer Channels over BlockingCollection because they integrate naturally with async/await and avoid blocking thread-pool threads.
Code example
var channel = Channel.CreateBounded<WorkItem>(new BoundedChannelOptions(512)
{
FullMode = BoundedChannelFullMode.Wait, // back-pressure: producer awaits
SingleReader = false,
SingleWriter = false
});
// Producer
await channel.Writer.WriteAsync(new WorkItem(), cancellationToken);
channel.Writer.Complete(); // signal no more items
// Consumer
await foreach (var item in channel.Reader.ReadAllAsync(cancellationToken))
await ProcessAsync(item);
Follow-up
When would you choose Channel<T> over Dataflow's BufferBlock<T>? What is the difference in back-pressure behaviour?