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

查看:41
本文介绍了.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".

参考源(非合同,当然).

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

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