csharp / expert
Snippet
High-Performance Streaming with System.Threading.Channels
System.Threading.Channels provides a highly optimized, asynchronous producer-consumer queue. Unlike ConcurrentQueue, it natively supports async/await for waiting on space (Writer) or items (Reader). Bounded channels allow for backpressure management, ensuring that a fast producer doesn't overwhelm the system memory when the consumer is slow.
snippet.csharp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
using System.Threading.Channels;var channel = Channel.CreateBounded<int>(new BoundedChannelOptions(100) {FullMode = BoundedChannelFullMode.Wait});// Producer_ = Task.Run(async () => {for (int i = 0; i < 1000; i++)await channel.Writer.WriteAsync(i);channel.Writer.Complete();});// Consumerawait foreach (var item in channel.Reader.ReadAllAsync()) {Process(item);}
Breakdown
1
Channel.CreateBounded<int>(100)
Creates a thread-safe queue with a fixed capacity of 100 items.
2
await channel.Writer.WriteAsync(i)
Asynchronously waits if the channel is full before adding the item.
3
channel.Reader.ReadAllAsync()
Returns an IAsyncEnumerable that yields items as they become available until the channel is closed.