Is there a difference between calling .Result or waiting on known completed tasks?
Is there any functionality, performance or risk of breaking deadlock in the following code blocks?
Example 1:
await Task.WhenAll(task1, task2);
var result1 = await task1;
var result2 = await task2;
Example 2:
await Task.WhenAll(task1, task2);
var result1 = task1.Result;
var result2 = task2.Result;
source to share
Is there any functionality, performance or risk of breaking deadlock in the following code blocks?
No, there is no such case.
In both cases, the task is created, which will be completed when will be completed task1
and task2
.
Hence, when you write:
var result1 = await task1;
var result2 = await task2;
the code will be executed in sync. For something is not necessary await
, since the two of you task1
and task2
should have been completed.
The same is true for the second example where you are trying to get their results.
var result1 = task1.Result;
var result2 = task2.Result;
Since the tasks are already completed, you are not blocking the threading thread or have no context switch, etc.
Update
The only functional difference between the two approaches is that error handling is different. await
just unpacks AggregateException
and .Result
just throws an exception.
source to share