using System.Threading.Tasks;
using System.Threading.Channels;
using System.Diagnostics;
public static void Main()
Channel<int> channel = Channel.CreateBounded<int>(10);
Task producer = Task.Run(async () =>
Stopwatch stopwatch = Stopwatch.StartNew();
Connection connection = new();
while (stopwatch.ElapsedMilliseconds < 1000)
await channel.Writer.WaitToWriteAsync();
Print($"Opening connection -->");
item = connection.GetNextItem();
Print($"Produced #{item}");
if (!channel.Writer.TryWrite(item)) break;
Print($"Closing connection <--");
await channel.Writer.WriteAsync(item);
Print($"Producer completed");
channel.Writer.Complete();
} catch (Exception ex) { channel.Writer.Complete(ex); }
Task consumer = Task.Run(async () =>
await foreach (var item in channel.Reader.ReadAllAsync())
Print($"Consuming: {item}");
Task.WaitAll(producer, consumer);
public void Open() => Thread.Sleep(100);
public void Close() => Thread.Sleep(100);
public int GetNextItem() => ++_index;
private static void Print(object value)
Console.WriteLine($@"{DateTime.Now:HH:mm:ss.fff} [{Thread.CurrentThread
.ManagedThreadId}] > {value}");