I have some working code. but I am not entirely sure what the best practice is, while working with Task.WhenAll. I found different blog post's using different approaches, but none of them stating why they went with their approach. The only "good" posts I found, was using Task.WhenAll, to fetch similar data and combining the result. But my use-case is I several data-sources with different data, that I have to do some work on.
The approach that I went with was:
var weatherTask = GetWeatherAsync();
var locationTask = GetLocationAsync();
var driversTask = GetDriversAsync();
await Task.WhenAll(weatherTask, locationTask, driversTask)
var weather = await weatherTask;
var location = await locaitonTask;
var drivers = await driversTask;
Mainly because I liked the way it looked / readability. But I also had thought about using the following other approach:
var weatherTask = GetWeatherAsync();
var locationTask = GetLocationAsync();
var driversTask = GetDriversAsync();
await Task.WhenAll(weatherTask, locationTask, driversTask)
var weather = weatherTask.Result;
var location = locaitonTask.Result;
var drivers = driversTask.Result;
The thought behind this approach was, that the tasks already was done and it would be save to use the .Result. But I stuck with the first approach. Because I was not entirely sure about the overhead of 'await' (if any).
So I came here in hope of some smart people knew the answer.
*** Edit I have looked at Awaiting multiple Tasks with different results
The answer to that post is:
You can also use Task.Result (since you know by this point they have all completed successfully). However, I recommend using await because it's clearly correct, while Result can cause problems in other scenarios.
But not if there is any performance, using one over the other.
******** Edit Taking the example to the extreme. Look at these 2 loops.
for(int i=0; i< 1.000.000.000; i++)
{
var weatherTask = GetWeatherAsync();
var locationTask = GetLocationAsync();
var driversTask = GetDriversAsync();
await Task.WhenAll(weatherTask, locationTask, driversTask)
var weather = await weatherTask;
var location = await locaitonTask;
var drivers = await driversTask;
}
vs
for(int i=0; i< 1.000.000.000; i++)
{
var weatherTask = GetWeatherAsync();
var locationTask = GetLocationAsync();
var driversTask = GetDriversAsync();
await Task.WhenAll(weatherTask, locationTask, driversTask);
var weather = weatherTask.Result;
var location = locaitonTask.Result;
var drivers = driversTask.Result;
}
Would they both be just as quick? Or would the Task.Result be much faster?