Menu

Monday, 6 January 2025

Task.WhenEach in .NET9

 About


The series of features exploring in .NET 9 posts, This post, we are focusing on "Task.WhenEach" feature in .NET9. Please refer the following links for other .NET 9 features discussed in my earlier posts.

Introduction


Task.WhenEach is introduced in C#13 of .NET9. This is really helpful when we have list of tasks that completes in different time intervals and then we want to start other task as soon as it completes the current one. 

The below code example illustrates the usage of this feature by comparing/understand the earlier version with current version as well.


public async Task TaskWhenEachFeature()
{
    // Before            
    var tasks1 = Enumerable.Range(1, 5)
       .Select(async i =>
       {
           await Task.Delay(1000);
           return $"Task is {i} done in earlier.";
       })
       .ToList();

    
    while (tasks1.Count > 0)
    {
        var completedTask = await Task.WhenAny(tasks1);
        tasks1.Remove(completedTask);
        Console.WriteLine(await completedTask);
    }

    // .NET 9 USAGE OF Task.WhenEach feature
    Console.WriteLine("==.NET9 - Task.WhenEach feature");
    var tasks2 = Enumerable.Range(1, 5)
       .Select(async i =>
       {
           await Task.Delay(2000);
           return $"Task In .NET9 {i} done";
       })
       .ToList();
    await foreach (var completedTask in Task.WhenEach(tasks2))
        Console.WriteLine(await completedTask);
}

Screenshots




Output




No comments:

Post a Comment