Producer-Consumer Pattern Implementation in C#
14-day free trial
Try SeekerPro free for 14 days.
Full access while you try it · then $15.99/mo · cancel anytime
Start your 14-day free SeekerPro trial →30-day money-back guarantee · Cancel anytime
Not checking a site today? Turn your Concurrency question into a ready to paste AI prompt, free →
Key Takeaways
- ✓Producer-Consumer Pattern runs in O(1) per op time and O(n) space, in C# as in every other language.
- ✓System.Threading.Channels is the modern answer and is purpose-built for this pattern: Channel.CreateBounded<T>(new BoundedChannelOptions(capacity)) gives an async-friendly bounded queue whose WriteAsync suspends rather than blocking when full, and ChannelReader<T>.ReadAllAsync() is consumed with await foreach.
- ✓Prefer Channels over BlockingCollection for anything async, because Channels never block a thread-pool thread.
- ✓The C# trap: Forgetting writer.Complete() leaves every consumer awaiting ReadAllAsync forever, and like the Swift case it is a silent stall rather than a visible hang.
- ✓Channels are allocation-light and lock-free on the fast path, with per-item cost in the tens of nanoseconds, substantially cheaper than BlockingCollection, which takes a lock and can block an OS thread.
What Producer-Consumer Pattern actually is
Producer-Consumer Pattern in C#: what you actually reach for
C# implementation
using System;
using System.Threading;
using System.Threading.Channels;
using System.Threading.Tasks;
public static class Pipeline
{
public static async Task RunAsync(int workers, CancellationToken ct)
{
// BOUNDED + explicit overflow behaviour. CreateUnbounded removes backpressure.
var channel = Channel.CreateBounded<int>(new BoundedChannelOptions(1024)
{
FullMode = BoundedChannelFullMode.Wait,
SingleWriter = true,
});
var consumers = new Task[workers];
for (int i = 0; i < workers; i++)
{
consumers[i] = Task.Run(async () =>
{
await foreach (var item in channel.Reader.ReadAllAsync(ct))
await HandleAsync(item, ct);
}, ct);
}
for (int i = 0; i < 10_000; i++)
await channel.Writer.WriteAsync(i, ct); // suspends when full
channel.Writer.Complete(); // omit this and ReadAllAsync NEVER completes
await Task.WhenAll(consumers);
}
private static Task HandleAsync(int item, CancellationToken ct) => Task.CompletedTask;
// Never .Result / .Wait() on these: blocking a pool thread that the
// completion needs starves the pool and can deadlock the pipeline.
}Think Your Code Is Clean? Let NexusBro QA It in 20 Seconds.
Paste your code. Click QA. Get an instant expert-level audit with fixes.
QA My Code FreeThe C#-specific trap
Performance in C#, beyond the O(1) per op
Real-World Applications
Interview Tips & Practice
Frequently Asked Questions
Which C# type or library should I use for Producer-Consumer Pattern?
System.Threading.Channels is the modern answer and is purpose-built for this pattern: Channel.CreateBounded<T>(new BoundedChannelOptions(capacity)) gives an async-friendly bounded queue whose WriteAsync suspends rather than blocking when full, and ChannelReader<T>.ReadAllAsync() is consumed with await foreach. BoundedChannelFullMode chooses the overflow behaviour (Wait, DropOldest, DropNewest, DropWrite). BlockingCollection<T> is the older synchronous equivalent.
What is the most common C# mistake when implementing Producer-Consumer Pattern?
Forgetting writer.Complete() leaves every consumer awaiting ReadAllAsync forever, and like the Swift case it is a silent stall rather than a visible hang. Channel.CreateUnbounded is the convenient constructor and is unbounded exactly as named, it removes the backpressure that is the reason to use a channel. And the general .NET trap applies here more than anywhere: blocking on an async channel operation with .Result or .Wait() occupies a pool thread that the completion needs, which starves the pool and can deadlock the pipeline outright.
How does Producer-Consumer Pattern actually perform in C#?
Channels are allocation-light and lock-free on the fast path, with per-item cost in the tens of nanoseconds, substantially cheaper than BlockingCollection, which takes a lock and can block an OS thread. Setting SingleReader = true lets the implementation skip reader synchronisation entirely. A bounded capacity that is too large mostly delays the moment you discover the consumer is too slow, so prefer a small bound plus explicit overflow handling. Time complexity is O(1) per op and space is O(n).
Related Articles
Rather try before you buy?
Get the rest of the vault: every cheat sheet, guide and audit in SeekerPro, free for 14 days, then $15.99/mo. Cancel anytime. Daily usage limits apply.
Start my 14-day SeekerPro trialIf you are a student, see what GitHub Copilot offers students for free on Noizz.
Is your site built to last?
Run a free QA audit and get your Site Health Score in seconds.
Check Your Site FreeNo signup required
Reader comments
No account needed. Share what worked, what did not, and what you would add.
Add your take below. A concrete tip, a result or a question helps the next reader most.