I have a simple question with async programming exposed by the following example:
foreach (var item in result)
{
property1 = await GetObjectivesQueryable(ObjectiveType.Company, from, to).SumAsync(x => x.ValeurObjectif);
property2 = await GetObjectivesQueryable(ObjectiveType.Company, new DateTime(DateTime.Now.Year, 1, 1), new DateTime(DateTime.Now.Year, 12, DateTime.DaysInMonth(DateTime.Now.Year, 12)).AddHours(23).AddMinutes(59).AddSeconds(59)).SumAsync(x => x.ValeurObjectif);
}
or the alternative:
foreach (var item in result)
{
var task1 = GetObjectivesQueryable(ObjectiveType.Company, from, to).SumAsync(x => x.ValeurObjectif);
var task2 = GetObjectivesQueryable(ObjectiveType.Company, new DateTime(DateTime.Now.Year, 1, 1), new DateTime(DateTime.Now.Year, 12, DateTime.DaysInMonth(DateTime.Now.Year, 12)).AddHours(23).AddMinutes(59).AddSeconds(59)).SumAsync(x => x.ValeurObjectif);
await Task.WhenAll(task1, task2);
property1 = task1.Result;
property2 = task2.Result;
}
From what i understand about async programming the first example above will execute the first instruction, block the execution thread until it complete with the await keyword then fill the property. Then redoing this step for the second property.
At the opposite the second example will asynchronously execute the both task and block the execution thread during the WhenAll instruction, then when both of the tasks are completed it will synchronously set property 1 and property 2.
So From my conclusion in this use case the second example is more performing.
Do my knowledge about async in this case is right?
Thanks in advance.
Despite being imprecise about the thread being blocked (which is incorrect as pointed out in the comments), you are correct.
While 'more performing' may mean many things, assuming that both operations are independent, Task.WhenAll option will finish earlier.
Having
var work1 = async () => await Task.Delay(1000);
var work2 = async () => await Task.Delay(2000);
await work1();
await work2();
will take 3 seconds, and
await Task.WhenAll(work1(), work2());
will take 2 seconds.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With