Skip to content

Instantly share code, notes, and snippets.

@bitbonk
Last active February 8, 2019 15:51
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/aa2da73dcae3b653abbfe41a11482e75 to your computer and use it in GitHub Desktop.
Save bitbonk/aa2da73dcae3b653abbfe41a11482e75 to your computer and use it in GitHub Desktop.
System.Threading.Channels (C# 8)
namespace ChannelTest
{
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
});
var write = 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();
});
var read = Task.Run(
async () =>
{
await foreach(var item in channel.Reader.ReadAllAsync())
{
Console.WriteLine($"Received {item} on Thread {Thread.CurrentThread.ManagedThreadId}");
}
});
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