CSharp · Console
using System;
using System.Threading;
using System.Threading.Channels;
using System.Threading.Tasks;
class Program
{
static async Task Main()
{
var channel = Channel.CreateUnbounded<int>();
for (int i = 1; i <= 10; i++) channel.Writer.TryWrite(i);
int itemsRead = 0;
var cts = new CancellationTokenSource();
try
{
await foreach (var i in channel.Reader.ReadAllAsync(cts.Token))
{
Console.WriteLine($"Read item: {i}. Requested cancellation: " +
$"{cts.Token.IsCancellationRequested}");
if (++itemsRead > 4 && !cts.IsCancellationRequested)
{
Console.WriteLine("Cancelling...");
cts.Cancel();
}
}
}
catch (OperationCanceledException)
{
Console.WriteLine($"Operation cancelled. Items read: {itemsRead}");
}
}
}