I have a situation like this:
var retrievalTasks = new Task[2];
retrievalTasks[0] = GetNodesAsync();
retrievalTasks[1] = GetAssetsToHandleAsync();
Task.WaitAll(retrievalTasks);
And I would like the result of retrievalTasks[0]
and retrievalTasks[1]
to be stored in variables.
I could achieve this with:
var a = await GetNodesAsync();
var b = await GetAssetsToHandleAsync();;
But I would rather not await both like that, because then they're not fired at the same time right? Or am I misunderstanding?
I've seen this as a reference: Awaiting multiple Tasks with different results
But I think this is a slightly different scenario that wouldn't work in my case.
Any ideas?
Thanks
EDIT:
await Task.WhenAll(catTask, houseTask, carTask);
var cat = await catTask;
var house = await houseTask;
var car = await carTask;
This just seemed to wait four times to get the three results. However, @armenm has shown how to avoid that.
Here we go, you need to have separate variables for the tasks having respective types:
var task1 = GetNodesAsync();
var task2 = GetAssetsToHandleAsync();
Task.WaitAll(new Task[] { task1, task2 });
var result1 = task1.Result;
var result2 = task2.Result;
But I would recommend to make it asynchronous:
var task1 = GetNodesAsync();
var task2 = GetAssetsToHandleAsync();
await Task.WhenAll(new Task[] { task1, task2 });
var result1 = task1.Result;
var result2 = task2.Result;