.Wait()与.GetAwaiter().GetResult()有什么区别? [英] What is the difference between .Wait() vs .GetAwaiter().GetResult()?

查看:83
本文介绍了.Wait()与.GetAwaiter().GetResult()有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的方法返回Task.我要等到完成.我应该用什么 .Wait()还是.GetAwaiter().GetResult()?它们之间有什么区别?

My method returns Task. I want to wait until it finished. What should I use .Wait() or .GetAwaiter().GetResult()? What is the difference between them?

推荐答案

两者都是同步等待操作的结果(如果可能,应避免使用它们).

Both are a synchronous wait for the result of the operation (and you should avoid those if possible).

区别主要在于处理异常.使用Wait时,异常堆栈跟踪不会更改,并且表示发生异常时的实际堆栈,因此,如果您有一段在线程池线程上运行的代码,则您将拥有一个类似

The difference is mainly in handling exceptions. With Wait, the exception stack trace is unaltered and represents the actual stack at the time of the exception, so if you have a piece of code that runs on a thread-pool thread, you'd have a stack like

ThreadPoolThread.RunTask
YourCode.SomeWork

另一方面,.GetAwaiter().GetResult()将重做堆栈跟踪以考虑所有异步上下文,而忽略代码的某些部分在UI线程上执行,某些在ThreadPool线程上执行,而有些则是异步的I/O.因此,您的堆栈跟踪将通过您的代码

On the other hand, .GetAwaiter().GetResult() will rework the stack trace to take all the asynchronous context into account, ignoring that some parts of the code execute on the UI thread, and some on a ThreadPool thread, and some are simply asynchronous I/O. So your stack trace will reflect a synchronous-like step through your code:

TheSyncMethodThatWaitsForTheAsyncMethod
YourCode.SomeAsyncMethod
SomeAsync
YourCode.SomeWork

至少可以这样说,这倾向于使异常堆栈跟踪更有用.您可以看到在应用程序上下文中YourCode.SomeWork被称为的位置,而不是运行它的物理方式".

This tends to make exception stack traces a lot more useful, to say the least. You can see where YourCode.SomeWork was called in the context of your application, rather than "the physical way it was run".

参考源(当然不是合同制的.)

An example of how this works is in the reference source (non-contractual, of course).

这篇关于.Wait()与.GetAwaiter().GetResult()有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆