A couple years ago I was a little stuck on implementing async/await for the first time. I got an answer to my question [on this site], and I went on my merry way.
But lately, I got called out saying "that's not running those calls in parallel", even though it was VERY close to the exact solution that I received earlier.
Now I'm having second thoughts.
Here's the background, and the possible resolutions.
The whole point is that I don't want to execute method 1, wait for the results, then execute method 2 and wait for those results. That's too slow when the two method calls have nothing to do with each other.
I want to perform two method calls, both of which happen to be going to a database, but it could be anything, and I don't want processing to continue until I have the result of both calls.
public async Task<DataViewModel> GetDataInParallel()
{
var asyncStuff = new
{
result1 = await _databaseRepo.QuerySomething(),
result2 = await _databaseRepo.QuerySomethingElse()
};
return new DataViewModel(asyncStuff.result1, asyncStuff.result2);
}
vs
public async Task<DataViewModel> GetDataInParallel()
{
var result1Task = _databaseRepo.QuerySomething();
var result2Task = _databaseRepo.QuerySomethingElse();
var asyncStuff = new
{
result1 = await result1Task,
result2 = await result2Task
};
return new DataViewModel(asyncStuff.result1, asyncStuff.result2);
}
I use both versions in my website, but now I'm wondering if the ones that use option 1 are not doing things in parallel, and I'm seeing a performance degradation.
I'm not exactly sure on how to prove this out; does anyone know which is the correct version that will execute the two method calls in parallel? Or are they both right/wrong?