Complete these tasks to reinforce what you learned in this module.
Write an async iterator that waits briefly, then yields each number from 1 to count. Main consumes it with await foreach.
static async IAsyncEnumerable<int> Ticks(int count), with await Task.Delay(10); before each yield return.using System;
using System.Collections.Generic;
using System.Threading.Tasks;
class Program
{
static async IAsyncEnumerable<int> Ticks(int count)
{
// Wait a moment, then hand back each number from 1 to count
await Task.CompletedTask;
yield break;
}
static async Task Main()
{
await foreach (var tick in Ticks(3))
{
Console.WriteLine(tick);
}
}
}
Add up everything an async sequence produces and print the total, then print done. Use await foreach.
await foreach (var n in Values()) { total += n; } inside async Task Main.using System;
using System.Collections.Generic;
using System.Threading.Tasks;
class Program
{
static async IAsyncEnumerable<int> Values()
{
for (int i = 1; i <= 5; i++)
{
await Task.Delay(5);
yield return i;
}
}
static async Task Main()
{
// Sum everything Values() produces, print the total, then print done
}
}