Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a difference between calling .Result or await on known completed tasks? [duplicate]

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; 
like image 275
NStuke Avatar asked Apr 22 '15 21:04

NStuke


People also ask

Is .result the same as await?

await asynchronously unwraps the result of your task, whereas just using Result would block until the task had completed. See this explanantion from Jon Skeet.

What is the difference between task and async task?

Async methods are intended to be non-blocking operations. An await expression in an async method doesn't block the current thread while the awaited task is running. Instead, the expression signs up the rest of the method as a continuation and returns control to the caller of the async method.

Does task result block?

Yes Accessing Task. Result is the same as calling Task. Wait().


1 Answers

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.

like image 152
Christos Avatar answered Sep 24 '22 03:09

Christos