简体   繁体   English

GetAwaiter()。GetResult()与GetAwaiter()?

[英]GetAwaiter().GetResult() vs GetAwaiter()?

Most devs are using GetAwaiter().GetResult() , and I can barely dig up examples using it with without the GetResult() part, however it is illogical to use GetResult() when we don't need the result. 大多数开发人员都在使用GetAwaiter().GetResult() ,而没有GetResult()部分,我几乎无法使用它来挖掘示例,但是当我们不需要结果时使用GetResult()是不合逻辑的。

Is there a reason why not just use GetAwaiter() when applicable? 是否有理由GetAwaiter()在适用时使用GetAwaiter() Or is my perception of what the common usage is wrong? 还是我对常用用法有什么误解?

GetAwaiter() not waits for task, just returns TaskAwater object, which can be used to wait for task by calling GetResult() . GetAwaiter()不等待任务,仅返回TaskAwater对象,可以通过调用GetResult()来等待任务。 So calling GetAwaiter() only is meaningless. 因此,仅调用GetAwaiter()是没有意义的。 As documentation states this class is only intended of compiler use and users should not use it. 正如文档所述,此类仅用于编译器用途,用户不应使用它。 You should use Task.Wait() , when you want to wait for task, but not need result. 当您要等待任务但不需要结果时,应使用Task.Wait() But sometimes users still use Task.GetAwaiter().GetResult(), Instead of Task.Wait() in try-catch block because Task.GetAwaiter().GetResult() not wraps Exception thrown while executing task in AggregateException and also shows more detailed stack trace, that makes exception handling easier. 但有时用户仍然在try-catch块使用Task.GetAwaiter()调用getResult(),而不是Task.Wait(),因为Task.GetAwaiter()调用getResult()未包装Exception ,而在执行任务抛出AggregateException也说明更多详细的堆栈跟踪,这使得异常处理更加容易。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM