Last active
February 8, 2019 15:51
-
-
Save bitbonk/aa2da73dcae3b653abbfe41a11482e75 to your computer and use it in GitHub Desktop.
System.Threading.Channels (C# 8)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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