I’m trying to understand the difference between these two segments of code:
private async Task<ShopData> LoadShopData()
{
// These perform MongoDB queries
Task<IEnumerable<ShopMerchant>> fetchMerchants = _ShopSource.GetMerchants();
Task<IEnumerable<ShopMerchant>> fetchTiers = _ShopSource.GetTiers();
var shopData = new ShopData
{
ShopMerchants = (await fetchMerchants).ToList(),
ShopTiers = (await fetchTiers).ToList()
};
return shopData;
}
// Second option:
private async Task<ShopData> LoadShopData()
{
// These perform MongoDB queries
Task<IEnumerable<ShopMerchant>> fetchMerchants = _shopSource.GetMerchants();
Task<IEnumerable<ShopMerchant>> fetchTiers = _shopSource.GetTiers();
var tasks = new List<Task>
{
fetchMerchants,
fetchTiers
};
await Task.WhenAll(tasks);
var shopData = new ShopData
{
ShopMerchants = (fetchMerchants.Result).ToList(),
ShopTiers = (fetchTiers.Result).ToList()
};
return shopData;
}
I think the second one would be better, however in either case the main thread is not blocked because even in the first method the thread is free to continue with whatever work there was higher up the call stack when it hits the await
keywords.
Is the second method more performant only because the main method only has to return to continue working in LoadShopData()
once instead of twice?