Last active
March 11, 2020 12:48
-
-
Save ronnieoverby/c401c97bbf7702088a4e9ccd58f79732 to your computer and use it in GitHub Desktop.
An example when `Task.Yield()` is useful
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
var ch = Channel.CreateUnbounded<int>(); | |
var producer = Task.Run(() => | |
{ | |
for (int i = 0; i < 500_000; i++) | |
ch.Writer.WriteAsync(i); | |
ch.Writer.Complete(); | |
}); | |
Task.WaitAll( | |
Read(1), | |
Read(2), | |
Read(3), | |
producer); | |
async Task Read(int id) | |
{ | |
var dc = new DumpContainer().Dump(id.ToString()); | |
await Task.Yield(); // to prevent blocking when the producer has already written elements | |
await foreach (var x in ch.Reader.ReadAllAsync()) | |
dc.Content = x; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment