-2

My question really is, is there a technical reason why you should or not use Task.WhenAll()? Is it just a preference when I like these 2 tasks to run parallel. Or just using two await tasks, instead of WhenAll.

And may I know what is the different between

var aTask = aService.GetAContentAsync(request.Language);

var bTask = bService.GetBContentAsync(request.Language);

await Task.WhenAll(aTask, bTask);

var aResponse = aTask.Result;
var bResponse = bTask.Result;

var response = new Content
{
   Title = aResponse ,
   Details = bResponse 
};

And

var aTask = aService.GetAContentAsync(request.Language);

var bTask = bService.GetBContentAsync(request.Language);

await Task.WhenAll(aTask, bTask);

var aResponse = await aTask;
var bResponse = await bTask;

var response = new Content
{
   Title = aResponse ,
   Details = bResponse 
};

Or better to do as below

var aTask = aService.GetAContentAsync(request.Language);

var bTask = bService.GetBContentAsync(request.Language);

var allTasks = await Task.WhenAll(aTask, bTask);

var aResponse = allTasks[0];
var bResponse = allTasks[1];

var response = new Content
{
   Title = aResponse ,
   Details = bResponse 
};

Understand the different for code above and which is better

Avery Lam
  • 1
  • 1

1 Answers1

0

Task.WhenAll already returns the results in an array, and you seem to know this from your third example. Why would you await a second time to get them again?

Also, you cannot await ValueTasks a second time, it is explicitly mentioned by the documentation. So at best you're doing very inefficient work and at worst you're corrupting your task workflow.

Blindy
  • 65,249
  • 10
  • 91
  • 131