One way is to make each Task
responsible for storing its own result, and then all you have to do is await
the collection of Tasks. Note that you'll have to use await
to make the WhenAll()
execute the tasks that you pass into it.
var results = new int[3];
var tasks = new[] {
Task.Factory.StartNew(() => results[0] = GetSomething1()),
Task.Factory.StartNew(() => results[1] = GetSomething2()),
Task.Factory.StartNew(() => results[2] = GetSomething3())
};
await Task.WhenAll(tasks);
Console.WriteLine(results[0]);
Console.WriteLine(results[1]);
Console.WriteLine(results[2]);
Working demo: https://dotnetfiddle.net/HS32QA
Note that you may need to be careful with using e.g. a List<T>
instead of an array, and then calling list.Add(result)
, as there is no guarantee of the order in which the tasks are executed or when they will be finished.