Phase 23 of 30 · Topic 23.1

`System.Threading.Channels` vs `BlockingCollection<T>`

1Concept

`System.Threading.Channels` is a high-speed, zero-allocation asynchronous producer-consumer queue designed for modern async/await architectures, outperforming legacy synchronous `BlockingCollection<T>`.

2Architecture Diagram

[ Producer Tasks ] ──> channel.Writer.WriteAsync(item)
                                      │
                         [ Thread-Safe Channel Buffer ]
                                      │
[ Consumer Tasks ] <── await foreach (var item in channel.Reader.ReadAllAsync())

3Code Example

C# 13 & .NET 9
using System;
using System.Threading.Channels;
using System.Threading.Tasks;

public class BasicChannelDemo
{
    public static async Task Main()
    {
        var channel = Channel.CreateUnbounded<string>();

        // Producer Task
        _ = Task.Run(async () =>
        {
            for (int i = 1; i <= 3; i++)
            {
                await channel.Writer.WriteAsync($"LogEvent_{i}");
            }
            channel.Writer.Complete(); // Signals EOF
        });

        // Consumer Task
        await foreach (var item in channel.Reader.ReadAllAsync())
        {
            Console.WriteLine($"Consumed: {item}");
        }
    }
}

4Expected Output

Consumed: LogEvent_1
Consumed: LogEvent_2
Consumed: LogEvent_3

5Key Takeaways

  • Channels operate 100% non-blockingly with `ValueTask` return types.
  • Always call `channel.Writer.Complete()` when production finishes to terminate reader loops.
  • Memory allocations are near zero during high-throughput message streaming.