Skip to content

Instantly share code, notes, and snippets.

@bitbonk
Created January 19, 2019 18:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bitbonk/11b11f18529ade961c5aa6a37337a621 to your computer and use it in GitHub Desktop.
Save bitbonk/11b11f18529ade961c5aa6a37337a621 to your computer and use it in GitHub Desktop.
Hello World System.Threading.Channels
using System;
using System.Threading;
using System.Threading.Channels;
using System.Threading.Tasks;
class Program
{
public static async Task Main(string[] args)
{
var channel =
Channel.CreateBounded<int>(
new BoundedChannelOptions(100)
{
FullMode = BoundedChannelFullMode.Wait,
SingleReader = true,
SingleWriter = true,
AllowSynchronousContinuations = false
});
Task.Run(
async () =>
{
for (var i = 0; i < 100; i++)
{
Console.WriteLine($" Writing {i} on Thread {Thread.CurrentThread.ManagedThreadId}");
await channel.Writer.WriteAsync(i);
await Task.Delay(500);
}
channel.Writer.Complete();
});
Task.Run(
async () =>
{
try
{
while (true)
{
var item = await channel.Reader.ReadAsync();
Console.WriteLine($"Received {item} on Thread {Thread.CurrentThread.ManagedThreadId}");
}
}
catch (ChannelClosedException)
{
}
});
await channel.Reader.Completion;
Console.WriteLine("Completed!");
Console.ReadLine();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment