I need to run three async I/O operations in parallel, particularly they are the database calls. So, I write the following code:
// I need to know whether these tasks started running here
var task1 = _repo.GetThingOneAsync();
var task2 = _repo.GetThingTwoAsync();
var task3 = _repo.GetThingThreeAsync();
// await the results
var task1Result = await task1;
var task2Result = await task2;
var task3Result = await task3;
The GetThingOneAsync(), GetThingTwoAsync(), GetThingThreeAsync()
methods are pretty much the similar to each other except that they have different return types(Task<string>, Task<int>, Task<IEnumerable<int>>
). The example of one of the database calls is the following:
public async Task<IEnumerable<int>> GetThingOneAsync(string code)
{
return await db.DrType.Where(t => t.Code == code).Select(t => t.IdType).ToListAsync();
}
In debug mode I can see that var task1 = _repo.GetThingOneAsync();
started to run GetThingOneAsync()
async method (the same with other two tasks).
My colleagues say that _repo.GetThingOneAsync()
does not start the async operation. They say that the operation started when we reach await
(that statement seems to be wrong for me).
So, they suggest to fix my code to the following:
var task1 = _repo.GetThingOneAsync();
var task2 = _repo.GetThingTwoAsync();
var task3 = _repo.GetThingThreeAsync();
await Task.WhenAll(task1, task2, task3);
// then get the result of each task through `Result` property.
In my opinion, it's the same as I wrote in the very beginning of the question except that Task.WhenAll
waits for later tasks to finish if an earlier task faults (this is Servy's comment from this question)
I know that my question is kind of duplicate but I want to know whether I'm doing things right or wrong.