The C# method Task.WhenAll can run a bunch of async methods in parallel and returns when every one finished.
But how do you collect the return values?
Imagine that you have this pseudo-async-method:
private async Task<string> GetAsync(int number) { return DoMagic(); }
And you wish to call that method 20 times, and then collect all the results in a list?
That is a 3 step rocket:
- Create a list of tasks to run
- Run the tasks in parallel using Task.WhenAll.
- Collect the results in a list
// Create a list of tasks to run List<Task> tasks = new List<Task>(); foreach (int i=0;i<20;i++) { tasks.Add(GetAsync(i)); } // Run the tasks in parallel, and // wait until all have been run await Task.WhenAll(tasks); // Get the values from the tasks // and put them in a list List<string> results = new List<string>(); foreach (var task in tasks) { var result = ((Task<string>)task).Result; results.Add(result); }
MORE TO READ:
- Task.WhenAll from microsoft
- Run tasks in parallel using .NET Core, C# and async coding by briancaos
- Using C# HttpClient from Sync and Async code by briancaos
- Awaiting multiple Tasks with different results from stackoverflow
- Get the result of multiple tasks in a ValueTuple and WhenAll by Gérald Barré
- Using Task.WhenAny And Task.WhenAll by Hamid Mosalla
// This is a bit nicer (and shorter) I think
// Create a list of tasks to run
List<Task> tasks = new List<Task>();
foreach (int i=0;i<20;i++)
{
tasks.Add(GetAsync(i));
}
// Run the tasks in parallel, and
// wait until all have been run
// collecting the results at the same time
var results = await Task.WhenAll(tasks);
// the above is an array, but if a list is required this line could be used instead:
// var results = (await Task.WhenAll(tasks)).ToList();
LikeLike
// This is a bit nicer (and shorter) I think – my previous posting
// looked like the Task lost its generic parameter, string
// Create a list of tasks and start them running
List<Task> tasks = new List<Task>();
foreach (int i=0;i<20;i++)
{
tasks.Add(GetAsync(i));
}
// Wait until the running tasks have been run
// collecting the results at the same time
var results = await Task.WhenAll(tasks);
// the above is an array, but if a list is required this line could be used instead:
// var results = (await Task.WhenAll(tasks)).ToList();
LikeLike
Task.WhenAll does not run tasks!!
But for collecting all the results in one array, it is fine.
var results = await Task.WhenAll(tasks);
LikeLike