Is there a better to run async methods in parallel, or are tasks a good approach?
Yes, the “best” approach is to utilize the Task.WhenAll
method. However, your second approach should have ran in parallel. I have created a .NET Fiddle, this should help shed some light. Your second approach should actually be running in parallel. My fiddle proves this!
Consider the following:
public Task<Thing[]> GetThingsAsync()
{
var first = GetExpensiveThingAsync();
var second = GetExpensiveThingAsync();
return Task.WhenAll(first, second);
}
Note
It is preferred to use the “Async” suffix, instead of GetThings
and GetExpensiveThing
– we should have GetThingsAsync
and GetExpensiveThingAsync
respectively – source.