This article will review a straightforward way to return all the results from several Tasks which are run in batches. Batching your tasks will help manage resources on your servers so it is always a clever idea.
In your project, first install the batching NuGet package morelinq.
dotnet add package morelinq --version 4.1.0
With this package Batching is made much easier.
In our example I’ll be using a custom Cat object
class Cat
{
public string Name { get; set; }
public string Breed { get; set; }
}
We first create several tasks:
// Create a list of tasks that return Cat objects
List<Task<Cat>> tasks = new List<Task<Cat>>()
{
Task.Run(() => GetCat("Task 1")),
Task.Run(() => GetCat("Task 2")),
Task.Run(() => GetCat("Task 3"))
....and so on
};
Then we batch the calls, 5 at a time:
int batchSize=5;
foreach (var batch in tasks.Batch(batchSize))
await Task.WhenAll(batch.ToArray());
Next, we can pull all the Cat results out of the completed tasks:
// Retrieve the Cat objects from each task
List<Cat> cats = tasks.Select(task => task.Result).ToList();
Done!