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.
- CountBy LINQ in .NET 9
- AggregateBy LINQ in .NET 9
- Index LINQ in .NET 9
- UUID v7 in .NET9
- SearchValues improvements in .NET9
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);
}
No comments:
Post a Comment