是Task.Result相同.GetAwaiter.GetResult()? [英] Is Task.Result the same as .GetAwaiter.GetResult()?
问题描述
我最近读了大量采用了异步方法,但有时需要同步执行他们一些code。在code的作用:
I was recently reading some code that uses a lot of async methods, but then sometimes needs to execute them synchronously. The code does:
Foo foo = GetFooAsync(...).GetAwaiter().GetResult();
这是一样的。
Foo foo = GetFooAsync(...).Result;
推荐答案
pretty得多。一个小的差别是:如果在工作
失败,调用getResult()
将只是把直接导致异常,而 Task.Result
将抛出一个 AggregateException
。然而,什么是使用这类原因时,它的异步
的地步?该100X更好的选择是使用等待
。
Pretty much. One small difference though: if the Task
fails, GetResult()
will just throw the exception caused directly, while Task.Result
will throw an AggregateException
. However, what's the point of using either of those when it's async
? The 100x better option is to use await
.
此外,你不是要使用调用getResult()
。它的意思是编译器只使用,不适合你。但是,如果你不想让恼人的 AggregateException
,使用它。
Also, you're not meant to use GetResult()
. It's meant to be for compiler use only, not for you. But if you don't want the annoying AggregateException
, use it.
这篇关于是Task.Result相同.GetAwaiter.GetResult()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!