本文介绍了Task.Result 和 .GetAwaiter.GetResult() 一样吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我最近阅读了一些使用大量异步方法的代码,但有时需要同步执行它们.代码做:

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;

推荐答案

差不多.但是有一个小区别:如果 Task 失败,GetResult() 只会抛出直接引发的异常,而 Task.Result 会抛出一个 .但是,当它是 async 时,使用其中任何一个的意义何在?100 倍更好的选择是使用 await.

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() 一样吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-16 06:45