7

Is there any functional, performance, or risk of deadlock difference in the below 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; 
i3arnon
  • 113,022
  • 33
  • 324
  • 344
NStuke
  • 1,001
  • 8
  • 11
  • see http://stackoverflow.com/questions/24623120/await-on-a-completed-task-same-as-task-result – Alex Apr 22 '15 at 21:36
  • 1
    Result can cause deadlocks. Check this answer: http://stackoverflow.com/questions/24623120/await-on-a-completed-task-same-as-task-result – Cody Apr 22 '15 at 21:37
  • 1
    @Cody - In this case I believe it is impossible for it to deadlock as the task is already complete. – NStuke Apr 22 '15 at 21:40
  • 1
    @JacodeGroot - Stephen Clearly's answer on that question is pretty detailed, thanks for the link. In this case Task.WhenAll() would've already unwrapped the AggregateException, so that's not a concern. – NStuke Apr 22 '15 at 21:42

1 Answers1

12

Is there any functional, performance, or risk of deadlock difference in the below code blocks?

No, there isn't any such a case.

In both cases a task is created that will be completed when task1 and task2 would be completed.

Hence, when you write:

var result1 = await task1; 
var result2 = await task2;

the code will be executed synchronoulsy. You don't have to await for something, since you both task1 and task2 would have completed.

The same holds, for the second example, where you try to get their results.

var result1 = task1.Result;
var result2 = task2.Result; 

Since, the tasks have already completed, you don't block any thread calling thread or having any context switch etc.

Update

The only functional difference that exists between these two approaches is that the error handling is different. The await just unwraps an AggregateException, while .Result will just raise the exception.

Christos
  • 53,228
  • 8
  • 76
  • 108
  • 3
    There is a functional difference, error handling is different. `await` will unwrap a `AggregateException` where `.Result` will just raise the exception intact. – Scott Chamberlain Apr 22 '15 at 21:41
  • 1
    @ScottChamberlain thank you for your comment. I will include it in my answer. – Christos Apr 22 '15 at 21:42