I had a discussion today with a coworker. There was something fishy with his code, but I couldn’t tell what. I’ve realized I need to completely clarify once and for all how await works when launching multiple tasks. The code below demonstrates how the await operator ensures the code following the await does not execute until the task being awaited completes.


using System;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;

namespace ConsoleApp1
{
class Program
{
static void Main(string[] args)
{
DemoConsecutiveTasks().Wait();
}

private static async Task DemoConsecutiveTasks()
{
var itemsCount = 10000;
var items = Enumerable.Range(0, itemsCount);
var random = new Random();

Debug.Print("Beginning sequence of async invocations");

foreach (var item in items)
{
var currentValue = item;
Debug.Print($"Creating task for item {item}");
await Task.Run(
async () =>
{
var delay = random.Next(500, 1000);
Debug.Print($"Entering task {item}, delaying for {delay} milliseconds");
await Task.Delay(delay);
Debug.Print($"Executing task for index {currentValue}");
}
);
Debug.Print($"Returned from task {item}");
}
}
}
}

Advertisements