Join Nostr
2026-10-16 16:38:07 UTC

npub1u6…v0yg2 on Nostr: Learn: Producer-consumer with Channel<T> One part of the code produces work, another ...

Learn: Producer-consumer with Channel<T>

One part of the code produces work, another consumes it, and a queue sits between them. In .NET, Channel<T> is that queue, made for async code.

```csharp
var channel = Channel.CreateBounded<int>(2);
var producer = Task.Run(async () =>
{
for (int i = 1; i <= 3; i++) await channel.Writer.WriteAsync(i);
channel.Writer.Complete();
});
await foreach (int item in channel.Reader.ReadAllAsync()) Console.WriteLine(item);
await producer;
```

It prints 1, 2, 3. A bounded channel holds at most N items:

```csharp
var small = Channel.CreateBounded<int>(2);
Console.WriteLine($"{small.Writer.TryWrite(1)} {small.Writer.TryWrite(2)} {small.Writer.TryWrite(3)}");
```

It prints True True False: full. By default WriteAsync then waits; other modes drop items instead.

Read more: https://learn.microsoft.com/en-us/dotnet/core/extensions/channels

#tip · TIP-078