Skip to content

Instantly share code, notes, and snippets.

@ronnieoverby
Last active March 11, 2020 12:48
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 ronnieoverby/c401c97bbf7702088a4e9ccd58f79732 to your computer and use it in GitHub Desktop.
Save ronnieoverby/c401c97bbf7702088a4e9ccd58f79732 to your computer and use it in GitHub Desktop.
An example when `Task.Yield()` is useful
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