Await all Tasks in the list, and after that update the list base on task result

Viewed 1785

I want to run all tasks with WhenAll (not one by one). But after that I need to update list (LastReport property) base on result.

I think I have solution but I would like to check if there is better way.

Idea is to:

  • Run all tasks
  • Remember relation between configuration and task
  • Update configuration

My solution is:

var lastReportAllTasks = new List<Task<Dictionary<string, string>>>();
var configurationTaskRelation = new Dictionary<int, Task<Dictionary<string, string>>>();
foreach (var configuration in MachineConfigurations)
{
    var task = machineService.GetReports(configuration);
    lastReportAllTasks.Add(task);
    configurationTaskRelation.Add(configuration.Id, task);
}

await Task.WhenAll(lastReportAllTasks);
foreach (var configuration in MachineConfigurations)
{
    var lastReportTask = configurationTaskRelation[configuration.Id];
    configuration.LastReport = await lastReportTask;
}
3 Answers
Related