3

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.

Kieran
  • 612
  • 6
  • 22
  • Return type of both the functions should be same. – Saadi Jun 11 '18 at 09:56
  • What makes you think the one you've found doesn't work in your case? – James Thorpe Jun 11 '18 at 09:58
  • Because the answer is waiting all individually, i.e. await a, await b – Kieran Jun 11 '18 at 09:59
  • which makes me think they won't be fired at the same time – Kieran Jun 11 '18 at 09:59
  • That's just syntactic stuff at that point, they've been awaited in the `WhenAll`, in practice all the following `awaits` will run synchronously – James Thorpe Jun 11 '18 at 09:59
  • so are they awaiting twice in that example, or is it because it's already awaited it won't make a difference? – Kieran Jun 11 '18 at 10:00
  • Read through the comments etc under the answers - they go into more detail than is worth repeating here. If you still think it doesn't work for you, please edit your question with reasoning as to why not. – James Thorpe Jun 11 '18 at 10:04
  • I read through those comments, but it just looked like it would still be different. Maybe it's just my misunderstanding. However, this answer below is more suited to what I was attempting I think. – Kieran Jun 11 '18 at 10:17

1 Answers1

9

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;
armenm
  • 922
  • 6
  • 9
  • Thank you. I was trying to use result before. But I think the way I had it set up wouldn't allow it. – Kieran Jun 11 '18 at 10:12