调用.Result或等待已知的完成任务有什么区别吗? [英] Is there a difference between calling .Result or await on known completed tasks?
问题描述
以下代码块中是否存在功能,性能或死锁差异的风险?
Is there any functional, performance, or risk of deadlock difference in the below code blocks?
示例1:
await Task.WhenAll(task1, task2);
var result1 = await task1;
var result2 = await task2;
示例2:
await Task.WhenAll(task1, task2);
var result1 = task1.Result;
var result2 = task2.Result;
推荐答案
以下代码块中是否存在功能,性能或死锁差异的风险?
Is there any functional, performance, or risk of deadlock difference in the below code blocks?
不,没有这样的情况.
在这两种情况下,创建的任务都会在task1
和task2
完成时完成.
In both cases a task is created that will be completed when task1
and task2
would be completed.
因此,当您编写时:
var result1 = await task1;
var result2 = await task2;
代码将同步执行.您不必await
做某事,因为task1
和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.
更新
这两种方法之间存在的唯一功能差异是错误处理是不同的. await
只是解包AggregateException
,而.Result
只会引发异常.
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.
这篇关于调用.Result或等待已知的完成任务有什么区别吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!