In .NET 9, a new method, Task.WhenEach, has been introduced to streamline asynchronous programming. This method allows you to process tasks as they complete, rather than waiting for all tasks to finish. This is particularly useful in scenarios where tasks have varying completion times and you want to act on each one as soon as it's done.

Step 1. Create a function named PrintWithDelay

async Task<int> PrintWithDelay(int delay)
{
    await Task.Delay(delay);
    return delay;
}

This code defines an asynchronous method named PrintWithDelay that takes an integer delay as input and returns an integer.

async Task<int>

await Task.Delay(delay)

return delay

Step 2. Create a list of tasks that will each execute the PrintWithDelay method with different delay values.

List<Task<int>> printTasks = [
    PrintWithDelay(4000),
    PrintWithDelay(6000),
    PrintWithDelay(2000)
];

Step 3. Utilize Task.WhenEach in .NET 9.

Task.WhenEach yields an IAsyncEnumerable, allowing asynchronous processing of tasks as they complete.

await foreach (var task in Task.WhenEach(printTasks))
{
    Console.WriteLine(await task);
}

Task.WhenEach(printTasks)

await foreach (var task in Task.WhenEach(printTasks))

In short, the code does the following

Output

.NET 9 : Task.WhenEach

By leveraging Task.WhenEach, you can write more efficient and responsive asynchronous code in .NET 9.

Happy Coding!