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
Published at
2026-10-16 16:38:07 UTCEvent JSON
{
"id": "74f47a73615daa7158eecac4d46b22fcfa809cf0a735cfe1dcbed01ca46cb1e2",
"pubkey": "e68a0856e90d9997b1f721e905249896412dd570399a987b2e8fd5e7fcfe2279",
"created_at": 1792168687,
"kind": 1,
"tags": [
[
"t",
"tip"
]
],
"content": "Learn: Producer-consumer with Channel\u003cT\u003e\n\nOne part of the code produces work, another consumes it, and a queue sits between them. In .NET, Channel\u003cT\u003e is that queue, made for async code.\n\n```csharp\nvar channel = Channel.CreateBounded\u003cint\u003e(2);\nvar producer = Task.Run(async () =\u003e\n{\n for (int i = 1; i \u003c= 3; i++) await channel.Writer.WriteAsync(i);\n channel.Writer.Complete();\n});\nawait foreach (int item in channel.Reader.ReadAllAsync()) Console.WriteLine(item);\nawait producer;\n```\n\nIt prints 1, 2, 3. A bounded channel holds at most N items:\n\n```csharp\nvar small = Channel.CreateBounded\u003cint\u003e(2);\nConsole.WriteLine($\"{small.Writer.TryWrite(1)} {small.Writer.TryWrite(2)} {small.Writer.TryWrite(3)}\");\n```\n\nIt prints True True False: full. By default WriteAsync then waits; other modes drop items instead.\n\nRead more: https://learn.microsoft.com/en-us/dotnet/core/extensions/channels\n\n#tip · TIP-078",
"sig": "e555e3d7a5f0fbc9e6a8d4c15f185f274e5aeff77cd290c2cbbea248369df503cc1283f25fcb51a29ca8443f06711352db6e139e4a6b9d28a26dee546036b258"
}