C# & CLR Internals (50 Qs)•Part 2: Concurrency, Zero-Allocation & Advanced Language Features (11 - 24)
What is System.Threading.Channels and how does it outperform BlockingCollection?
senior LevelCode ExampleFormsGolang
In Simple Words:
System.Threading.Channels is a high-performance, fully asynchronous lock-free library for building producer-consumer patterns without thread blocking.
Why Channels Beat BlockingCollection:
BlockingCollection<T> blocks OS threads synchronously when waiting for items or buffer capacity. Channel<T> uses ValueTask and asynchronous awaiters, suspending tasks without holding any OS thread!
csharp
var channel = Channel.CreateBounded<OrderEvent>(new BoundedChannelOptions(10_000) {
FullMode = BoundedChannelFullMode.Wait,
SingleReader = true,
SingleWriter = false
});
// Non-blocking async producer:
await channel.Writer.WriteAsync(new OrderEvent(orderId));
// Non-blocking async consumer:
await foreach (var order in channel.Reader.ReadAllAsync()) {
ProcessOrder(order);
}