Introduction
System.Threading.Channels is the .NET library that provides channels for passing data between producers and consumers concurrently, with read and write APIs that work with async and await. I would use it when one stage generates work and another stage needs to consume it at a different pace, without forcing the producer to run the whole next stage or creating an independent task for every item.
A channel is an in-memory, in-process queue, not a message broker. A bounded channel can cap the growth of the buffer and apply backpressure: when the queue is full, the producer waits for space or the chosen policy drops items. That organizes the pressure between stages, but it provides no persistence, no processing acknowledgement and no recovery after the application crashes. If an order must survive a restart, Channels alone does not solve the problem.
Imagine an import that reads records faster than it can validate them. Accumulating everything in a list increases memory usage; creating thousands of tasks moves the queue into the scheduler and makes concurrency hard to control. A channel puts an explicit boundary between reading and processing. From that boundary, I can discuss capacity, number of consumers, saturation behavior and shutdown with verifiable decisions.
In this article, I will explain Channel<T>, ChannelWriter<T> and ChannelReader<T>, compare bounded and unbounded channels and show why accepting a write is not the same as finishing the work. I will also cover cancellation, completion and failures that can leave a producer blocked. The example is small, uses .NET 10 and deterministic tests, and has no database or external messaging.
The Git history analyzer (Portuguese) already applies Channels to a specific problem. Here, the goal is to understand the library and its lifecycle without repeating that analyzer. Afterwards, the same reasoning can help when implementing Workers, imports and local processing pipelines.
Prerequisites
- .NET SDK 10.0.400 or a compatible patch, as defined in the
global.jsonof the samples repository. - Familiarity with
Task,CancellationTokenandasync/await. No knowledge of a message broker is required. - Basic understanding of dependency injection if you adapt the example to a Worker or an API.
- A clone of blog-zocateli-sample to run the demo and read the complete tests.
In a project targeting the .NET 10 framework, the System.Threading.Channels types are already available through the framework references. The demo in this article does not need to add a Channels NuGet package. If you maintain a library for other frameworks, check the target frameworks and whether you need to reference the corresponding package.
The example data are integers generated in memory. That avoids confusing the channel’s behavior with database latency, network outages or the delivery guarantees of an external system.
Channel, Writer and Reader separate responsibilities
A Channel<T> represents the structure that connects writing and reading. Its Writer property returns a ChannelWriter<T>, which the producer uses to add items and to signal that no more writes will happen. The Reader property returns a ChannelReader<T>, which the consumer uses to take items or wait for them to arrive. This separation lets you hand each component only the capability it needs.
The producer does not need to know which consumer will receive an item. The consumer does not need access to the original data source. This is useful when the reading stage has a different nature from the processing stage: a parser can produce records incrementally while a small group of consumers applies validations. The shared contract is the type carried by the channel.
The structure already synchronizes its own operations. I would not wrap every write and read in an external lock out of habit. However, that protection does not extend to the content of the item: if the producer and the consumer keep mutating the same mutable object after the write, state is still shared. Prefer immutable data or a well-defined transfer of ownership.
Creating a channel also does not spawn a dedicated thread. Asynchronous operations wait for availability; the real work is still executed by the tasks you start. Channels coordinates the handoff of data; it does not decide on its own how many consumers will exist or what the right degree of parallelism is.
In code, this split shows up directly: Writer.WriteAsync admits work; Reader.ReadAllAsync supplies items for processing. The consuming service remains responsible for validating the data, executing the operation and handling its effects. A successful read is not a confirmation that the business operation finished.
A bounded channel applies backpressure; an unbounded one does not cap memory
An unbounded channel has no configured maximum capacity for its buffer. If the producer keeps advancing and the consumers cannot keep up, pending items can pile up. “Unbounded” describes the policy of the structure, not the amount of memory available to the process. The real limit is still imposed by the resources of the environment.
A bounded channel makes explicit how many items can remain in the buffer. In Wait mode, an asynchronous write waits for space when that capacity is reached. Instead of continuing to read a source and stacking objects, the producer receives pressure from the slowest stage. That is backpressure: the speed of one part of the pipeline influences the stage that feeds it.
| |
📂 Source Code: The complete example is available in the blog’s samples repository:
BlogSamples/AsyncParallel/Channels/
Capacity limits items waiting inside the channel, not all the work in flight. With four slots and two consumers, I can still have four items in the buffer and two being processed. Objects already created by the source, network buffers and tasks started outside that boundary also take memory. The channel does not impose a global ceiling on the process.
That is why I would size capacity and concurrency together. A very large queue can increase waiting time and memory without improving throughput; a small queue may be enough to smooth small differences in pace. Before choosing hundreds of slots, measure the size of the items, the consumer latency and the limits of the resource being accessed. The biggest number does not always produce the best flow.

Drop modes change the meaning of a write
BoundedChannelFullMode defines what happens when a write finds the buffer full. The default, Wait, keeps the intent of admitting every item by waiting for space on asynchronous writes. The other modes accept losing data at specific points. Choosing one of them is a functional decision: which information is the system allowed to abandon?
Consider a channel with capacity two, holding [10, 20], and an attempt to write 30 with no concurrent reads:
| Mode | Buffer result | Dropped item |
|---|---|---|
Wait | [10, 20] until space exists | None by policy; TryWrite(30) returns false |
DropWrite | [10, 20] | The new item 30 |
DropNewest | [10, 30] | The newest item already in the buffer: 20 |
DropOldest | [20, 30] | The oldest item in the buffer: 10 |
The name DropNewest deserves attention: it does not mean automatically discarding the incoming write. The channel removes the most recent item already stored, making room for the one that arrives. Confusing it with DropWrite can invert the intended policy.
In drop modes, TryWrite can return true even when an item was dropped by the policy. That return value does not prove that all data stayed in the queue, let alone that it was processed. The test in the example checks this behavior explicitly. To observe drops, channel creation can receive an itemDropped callback; keep that function small, safe and suitable for the concurrency of the writers.
I would consider DropOldest for replaceable view states when keeping every intermediate state is not a requirement. I would not use that policy for orders or audit trails that require a complete record. I also would not assume that dropping the oldest item creates a “last value per entity” rule: the policy acts on the queue and does not understand business keys.
⚠️ Warning: Dropping is a deliberate loss of information. Document the policy, count dropped items and confirm the domain tolerates that loss before using
DropWrite,DropNewestorDropOldest.
Asynchronous writing and reading require an explicit lifecycle
WriteAsync is a good choice when the producer must wait for space in a bounded channel. TryWrite makes an immediate attempt; in Wait mode, a full queue makes that attempt return false. Neither API should be interpreted as confirmation that the consumer finished its operation.
There are separate waiting APIs, such as WaitToWriteAsync and WaitToReadAsync, but an availability signal does not permanently reserve a slot or an item. Under concurrency, another task can take the space or remove the data before the next operation. Use the documented patterns and avoid building your own reservation protocol on top of an isolated check.
For a finite source, the producer must signal completion after the last write. TryComplete tries to close the writer without throwing the exception that a second call to Complete could cause. No new write is accepted after completion, but items already in the buffer can still be read.
On the normal path, ReadAllAsync makes that consumption straightforward:
| |
📂 Source Code: The complete example is available in the blog’s samples repository:
BlogSamples/AsyncParallel/Channels/
I would also await the consumer tasks. Reader.Completion represents the completion state of reading from the channel; it does not guarantee that a business operation already started with the last item has finished. Once the consumer takes an item, that item is no longer in the buffer. Only awaiting the consumers confirms that their delegates completed, and even that depends on the semantics of those delegates.
Multiple consumers share work, but they do not broadcast
A channel can accept multiple producers and multiple consumers. Each successful read removes an item from the queue for that reader; it does not deliver a copy to every consumer. If three consumers read the same channel, they share the work. If all of them need to receive every event, you need a different distribution strategy or dedicated channels for each subscription.
There is also a difference between dequeue order and completion order. Items available in the queue are taken according to the reading structure, but parallel consumers may take different amounts of time to process them. A later item can finish before an earlier one. This showed up in the demo: every integer was processed, but some console lines came out of numeric order.
If final order matters, do not promise to preserve it just because the data went through a queue. You can choose a single consumer, sort results by an explicit sequence number or partition by a key that defines the ordering unit. Each alternative has costs and limits; Channels does not choose that policy for you.
SingleWriter and SingleReader are declarations about the real usage of the channel and enable optimizations. They are not an authorization mechanism nor a way to force the rest of the program to use a single task. Set SingleReader = true only if there are no concurrent reads. In the example, that value depends on the configured number of consumers.
Finally, limit parallelism before starting expensive operations. Reading from the queue and creating a detached task for each item can empty the buffer quickly while putting thousands of operations in flight. In that design, backpressure is weakened: the bottleneck moved to a list of tasks the channel does not control.
Completion, cancellation and failure are not the same shutdown
On normal completion, the producer finishes its writes, closes the writer and the consumers drain the remaining items. If the intent is to process everything that was admitted, that path is different from immediately cancelling every read and operation. In a Worker, the time available for that draining also depends on the shutdown timeout configured by the host.
On cancellation, the intent is to stop the work cooperatively. Propagate the token to the write, the read, the source and the consumer operation. ReadAllAsync may still return data that is ready even after cancellation is requested; the example performs an explicit check before it starts processing an item. That does not automatically recover an item already taken from the queue.
On failure, you must prevent the surviving tasks from waiting forever. Imagine that the only consumer throws an exception while the producer is blocked in WriteAsync because there is no space. Simply awaiting Task.WhenAll does not cancel that producer. If nobody takes items anymore, it can keep waiting and prevent the whole group from finishing.
The example uses a linked cancellation source. The first recorded failure is preserved; the writer is completed with an error, the shared token is cancelled and the code awaits all tasks before propagating the failure. The policy is fail-fast: it does not promise to drain the buffer after the error. On normal completion, however, the buffer is drained.
There is no safe forced interruption of an arbitrary delegate that ignores cancellation. If the source or the processing gets stuck in an operation that does not honor the token, shutdown can keep taking time. Set timeouts on dependencies and verify cooperation. The channel manages its queue; it does not control the behavior of every external piece of code the pipeline calls.
When to choose Channels, Parallel.ForEachAsync or messaging
I would choose Channels when I need to separate stages, control a buffer and make the pressure between production and consumption explicit within the same process. If the problem is only iterating over a collection with a bounded degree of parallelism, Parallel.ForEachAsync may result in less coordination code. I would not add a channel just to make a loop look more sophisticated.
The article on parallelism in C# discusses tools for distributing work. Worker and Background Service covers execution outside the HTTP lifecycle. Channels can be used inside those scenarios, but it does not replace the Worker host nor define the concurrency policy of the dependencies.
An operation admitted into a local channel can be lost if the process crashes before consuming it. The channel keeps no persistent log, offers no business acknowledgement and does not automatically resend work whose consumer failed. Therefore, answering a request with “accepted” after enqueuing in memory is not the same as guaranteeing that the work will survive a restart.
For delivery between processes, resumption and persistence, evaluate a broker or another durable structure with guarantees suited to the domain. Even then, duplicates and consistency still require idempotency and a storage design. The Transactional Outbox Pattern addresses one of those boundaries.
Channels can work as an internal stage of a messaging consumer, but the external acknowledgement must follow the correct processing policy. Taking a message out of the channel is not enough reason to acknowledge it to the broker. The acknowledgement point must reflect the durable effects the application actually completed.
Practical Example
The complete example has a reusable pipeline and a standalone console app in AsyncParallel/Channels/Demo. The aggregator API does not need to be started. The producer generates twenty integers, two consumers run a short asynchronous operation and the queue admits four items in the buffer. On normal shutdown, the total must be twenty.
| |
📂 Source Code: The complete example is available in the blog’s samples repository:
BlogSamples/AsyncParallel/Channels/
Run it from the root of the samples repository:
| |
The order of the individual lines can change between runs. The relevant result on the normal path is the last line (the demo prints its messages in Portuguese):
| |
The tests verify normal completion with one and four consumers, producer failure, consumer failure, cancellation and the four full-buffer modes. The DropNewest case confirms that the removed item is the newest one already stored. Another case verifies that an item that was in the buffer can be read even after TryComplete receives an exception, before the faulted completion is observed.
While preparing this article, the ten cases passed by running the same source and test files in an isolated temporary xUnit project. The aggregator suite was blocked during restore by pre-existing security alerts on cryptographic dependencies; I did not disable the audit nor treat that suite as passing. The standalone console compiled and produced the expected total.
I do not present this demo as a benchmark. The five-millisecond wait represents a simulated asynchronous operation and helps visualize concurrency; it does not demonstrate a performance advantage of Channels. To measure a product, use your own load, item size and real dependencies, comparing throughput, latency, memory and losses.
Tips and Good Practices
- Start with small capacity and concurrency. Measure write waiting time and processing time before growing the buffer. More slots can increase the latency of pending work without speeding up the consumer.
- Record the saturation policy as a functional rule. Explain whether the system waits, rejects or drops, and which item can be lost. In drop modes, track the callback and do not use the write return value alone as a processing counter.
- Await the tasks, not just the channel. Closing the writer prevents new writes and lets the buffer drain. Completion of operations already started belongs to the consumers and must be awaited explicitly.
- Propagate cancellation and preserve the original failure. A failing consumer must release the producer waiting for space. Keep coordination centralized and verify that the source and external operations honor the tokens they receive.
- Do not detach one task per item without a limit. Fast dequeuing can hide the buildup of operations in flight. The limit has to reach the resource that actually processes the work.
- Do not confuse concurrency with broadcast or final ordering. Multiple readers split items and can finish out of order. If the domain needs copies for everyone or per-entity sequence, design that separately.
- Use persistence when the requirement demands it. An in-memory channel does not survive the process. For business commands, define durable delivery and idempotency instead of promising recovery the structure does not provide.
Objective Summary
- System.Threading.Channels carries data between producers and consumers in the same process, with concurrent read and write APIs compatible with asynchronous operations.
- A bounded channel in
Waitmode makesWriteAsyncwait for space when the buffer is full; capacity does not include items already taken and being processed. - Drop modes have distinct policies:
DropWriteloses the new write,DropNewestremoves the newest item already stored andDropOldestremoves the oldest item in the buffer. - An accepted write does not confirm processing. In drop modes,
TryWritecan returntrueeven though an item was lost by the policy. - Normal completion closes writes and lets the buffer drain; awaiting the consumer tasks is still necessary to track their operations.
- Failure and cancellation must be coordinated so that neither the producer nor the consumers wait forever. The example uses fail-fast on failures and cooperative cancellation.
- Multiple consumers split the work instead of receiving copies of every item, and they can complete operations out of input order.
- Persistence and cross-process delivery are not Channels guarantees; commands that must survive restarts require a durable strategy.
Read Also
- Git History for Debugging and Auditing at Scale (Portuguese) — a bounded Channel applied to an analysis pipeline, without replacing this library guide.
- .NET Worker and Background Service: High Volume — hosting and lifecycle of background processing.
- Asynchronous Programming in C#: async/await and Threads — fundamentals for understanding asynchronous waiting and cancellation.
- Parallelism in C#: Parallel, PLINQ and Tasks in Practice — alternatives when the problem does not need a pipeline with its own buffer.
- Transactional Outbox Pattern: Solving the Dual Write — consistency and durable delivery are different problems from in-memory coordination.
References
- Channels in .NET — concepts, channel creation and producer-consumer patterns.
- BoundedChannelFullMode — definition of the waiting and drop modes.
- ChannelWriter.TryWrite — immediate write attempt and the return value contract.
- ChannelReader.ReadAllAsync — asynchronous consumption and remarks on cancellation.
- ChannelWriter.TryComplete — completing the writer, including with an error.
- Cancellation in managed threads — the .NET cooperative cancellation model.
- Complete Channels example and tests — pipeline and console used in the article; the tests live in the matching
tests/BlogSamples.Tests/AsyncParallel/Channels/domain.

By commenting, you agree to our Privacy Policy, Terms of Use, Data Deletion Policy.