Created
January 19, 2019 18:23
-
-
Save bitbonk/11b11f18529ade961c5aa6a37337a621 to your computer and use it in GitHub Desktop.
Hello World System.Threading.Channels
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
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