1. Introduction
Today we step up a level! Time to meet a pretty special tool — Channel. This thing was made for modern asynchronous apps in .NET: where regular locks either don't help or seriously slow you down on your way to happiness.
You'll get familiar with the Producer-Consumer pattern, which hasn't lost relevance since the 1960s. You'll build a simple asynchronous "pipeline" where some threads or tasks produce stuff (for example, download files, compute numbers, wait for events) and other threads consume and process them (for example, save, write to a database, update the UI).
Why was Channel created?
- The Producer-Consumer pattern used to be solved with queues: the producer puts tasks into a queue, the consumer takes them out. But! BlockingCollection<T>, queues based on ConcurrentQueue<T>, even manual synchronization with lock — none of these are asynchronous. That means a thread can only block waiting for data, instead of returning control to the async/await scheduler.
- Asynchrony in .NET is not just a trendy word on Fridays, it's the foundation of modern architecture. Blocking threads to wait for items is expensive and inefficient. You need to wait for data without blocking — that's the problem Channel solves.
- Flexibility: channels let you build complex processing pipelines, separate producer/consumer logic, add intermediate steps and load balancing — all without low-level synchronization pain.
What is a Channel? (Analogy and architecture)
Imagine you have a relay baton (or a conveyor belt) that can carry objects from one place to another, and nobody needs to meet their colleague in person. The main thing is that the baton shouldn't get lost on the way.
Channel is a .NET primitive for asynchronous data transfer between different tasks, threads or parts of a program. It implements an asynchronous queue with support for awaiting both writes and reads.
- Producer puts items into the channel (for example, processing requests);
- Consumer takes items out — and job done!
2. The Channel<T> class and how it works
It all starts with the namespace:
using System.Threading.Channels;
Unlike regular collections, Channel is a factory that creates special objects for passing data.
Main types:
- ChannelWriter<T> — the "writer" (producer). Only inserts items.
- ChannelReader<T> — the "reader" (consumer). Only extracts items.
- The channel (Channel) separates responsibilities: the writer doesn't know about the reader and vice versa.
.NET has several channel implementations, each with its specifics: unbounded, bounded (limited capacity), single-producer-single-consumer (SPSC), multi-producer-multi-consumer (MPMC), etc. We'll start with the most generic one.
Simple example: an asynchronous task queue
using System;
using System.Threading.Channels;
using System.Threading.Tasks;
class Program
{
static async Task Main()
{
// Create an unbounded channel
var channel = Channel.CreateUnbounded<int>();
// Producer task
var producer = Task.Run(async () =>
{
for (int i = 0; i < 10; i++)
{
Console.WriteLine($"Producer: Puts {i} into the channel");
await channel.Writer.WriteAsync(i); // Asynchronous write!
await Task.Delay(100); // Simulate work
}
channel.Writer.Complete(); // Signal that we won't write more
});
// Consumer task
var consumer = Task.Run(async () =>
{
await foreach (var item in channel.Reader.ReadAllAsync())
{
Console.WriteLine($"Consumer: Got {item} from the channel");
await Task.Delay(200); // Simulate processing
}
Console.WriteLine("Consumer: Channel closed");
});
await Task.WhenAll(producer, consumer);
}
}
What's happening here?
- Channel.CreateUnbounded<int>() — create an unbounded channel.
- The producer writes numbers from 0 to 9 into the channel using WriteAsync.
- After finishing writes, it calls Complete() — a "No more items!" signal.
- The consumer iterates all items via ReadAllAsync() (also asynchronous) until the channel closes.
- Delays (Task.Delay) simulate real work: you can see items are written faster than they're read.
3. Why is this asynchronous?
Regular blocking queues (for example, BlockingCollection or collections protected with lock) can only block a thread. That means you waste precious resources if you have many tasks or want maximum throughput.
With channels:
- If producers are faster, the channel accumulates items (limited only by memory or the configured maximum size).
- If consumers are faster, they'll await until something appears (and won't block a thread, instead freeing it for the scheduler).
This is ideal for scenarios where you don't know in advance who's faster — producers or consumers.
Real-world uses
- Asynchronous logging: writing messages to a file/db happens in a separate task;
- Processing web requests: one task downloads a batch of pages, another analyzes their contents;
- Scanning and indexing folders: some tasks walk the filesystem, others compute statistics about files;
- Complex data pipelines: e.g., in ETL (Extract–Transform–Load) jobs one step turns raw data into intermediates, another turns them into the final product.
4. Bounded Channel
"Unlimited" channels are fun, but memory is not infinite (even if your machine feels huge).
A bounded channel lets you set the maximum number of items that can be inside at once. If the channel is full, the producer waits until the consumer removes something.
Example:
var channel = Channel.CreateBounded<int>(new BoundedChannelOptions(3)
{
FullMode = BoundedChannelFullMode.Wait // (default) - wait until space frees up
});
Only three items can be in the channel at the same time. If the producer tries to write a fourth — it will wait.
Multiple producers and consumers
var channel = Channel.CreateUnbounded<int>();
// 2 producers
for (int producerId = 0; producerId < 2; producerId++)
{
Task.Run(async () =>
{
for (int i = 0; i < 5; i++)
{
int value = producerId * 100 + i;
Console.WriteLine($"Producer {producerId}: Puts {value}");
await channel.Writer.WriteAsync(value);
await Task.Delay(50);
}
// Each producer calling Complete() — dangerous!
});
}
// Trick: Complete() should be called only once, when ALL producers have finished.
// For the example we'll leave a single consumer task:
Task.Run(async () =>
{
await foreach (var item in channel.Reader.ReadAllAsync())
{
Console.WriteLine($"Consumer got {item}");
await Task.Delay(100);
}
});
Warning! The channel should be closed (via Complete()) only after all producers finish. Otherwise others might try to write while the channel is already closed! In real apps people usually use a task counter or Task.WhenAll for this.
5. Practice: Processing images through a channel
Let's complicate the task a bit! Imagine you have a folder with images. One task finds images and puts their paths into the channel, another takes a path and does something useful with the file (for example, reads size or converts it).
Note: For simplicity the example will work with file names (without actual image processing), but the idea is the same.
using System;
using System.IO;
using System.Threading.Channels;
using System.Threading.Tasks;
class Program
{
static async Task Main()
{
var channel = Channel.CreateBounded<string>(5);
// Producer: finds .jpg files in the folder
var producer = Task.Run(async () =>
{
foreach (var file in Directory.EnumerateFiles(@"images", "*.jpg"))
{
await channel.Writer.WriteAsync(file);
Console.WriteLine($"Added to queue: {file}");
await Task.Delay(50); // simulate search delay
}
channel.Writer.Complete(); // end of queue
});
// Consumer: reads and "processes" files
var consumer = Task.Run(async () =>
{
await foreach (var file in channel.Reader.ReadAllAsync())
{
Console.WriteLine($"Processing file: {file}");
await Task.Delay(200); // simulate processing
}
Console.WriteLine("All images processed!");
});
await Task.WhenAll(producer, consumer);
}
}
6. Configuring Channel: options and nuances
Channels can be configured via options at creation time — here are the main parameters for bounded channels:
| Option | Description |
|---|---|
|
Maximum number of items that can be in the channel at once |
|
true if you have only one producer (speeds things up) |
|
true if you have only one consumer (speeds things up) |
|
What to do when the channel is full? Possible values: Wait, DropWrite, DropOldest, DropNewest |
Example with options:
var options = new BoundedChannelOptions(10)
{
SingleWriter = false,
SingleReader = true,
FullMode = BoundedChannelFullMode.Wait
};
var channel = Channel.CreateBounded<string>(options);
7. Async methods: ReadAsync, WriteAsync, ReadAllAsync
Why is async so important?
Methods WriteAsync and ReadAsync don't block a thread! If there's nothing to read — the task is paused, freeing the thread for other work. This is critical for server and UI apps where extra blocking can cause freezes.
ReadAllAsync — a convenience of modern C#
You can iterate asynchronously:
await foreach (var item in channel.Reader.ReadAllAsync())
{
// Work with item
}
Channel<T> vs thread-safe collections: what's the difference?
ConcurrentQueue<T>/BlockingCollection<T> are good for thread scenarios, but not ideal for pure async (await) flows.
Channel<T> was designed specifically for asynchronous pipeline apps. In terms of thread-safety both kinds handle concurrency well, but channels give flexibility and integration with modern C# features (IAsyncEnumerable and others).
8. Errors and common pitfalls
Don't forget to call Complete() on the writer when all items are added! Otherwise the consumer will hang waiting for new items forever.
Don't call Complete() multiple times if there are many writers — do it only after absolutely all producers have finished.
After the channel is closed you can't write items anymore, but you can still read the remaining ones.
Race condition on concurrent writes: if the channel is closed while someone still tries to write — you'll get an exception.
GO TO FULL VERSION