[英]What is the difference between .Wait() vs .GetAwaiter().GetResult()?
My method returns Task
.我的方法返回
Task
。 I want to wait until it finished.我想等到它完成。 What should I use
.Wait()
or .GetAwaiter().GetResult()
?我应该使用什么 .Wait(
.Wait()
或.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). 两者都是同步等待操作的结果(如果可能的话,你应该避免这些)。
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 使用
Wait
,异常堆栈跟踪不会改变并表示异常时的实际堆栈,因此如果您有一段代码在线程池线程上运行,那么您将拥有一个堆栈
ThreadPoolThread.RunTask
YourCode.SomeWork
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. 另一方面,
.GetAwaiter().GetResult()
将重写堆栈跟踪以考虑所有异步上下文,忽略代码的某些部分在UI线程上执行,而某些部分在ThreadPool线程上执行,有些是简单的异步I / O. So your stack trace will reflect a synchronous-like step through your code : 因此,您的堆栈跟踪将反映代码中的同步步骤:
TheSyncMethodThatWaitsForTheAsyncMethod
YourCode.SomeAsyncMethod
SomeAsync
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". 您可以在应用程序的上下文中查看调用
YourCode.SomeWork
,而不是“运行它的物理方式”。
An example of how this works is in the reference source (non-contractual, of course). 这是如何工作的一个例子是在参考源 (当然是非契约的)。
Try your best to avoid synchronously blocking on an asynchronous task.尽量避免同步阻塞异步任务。
In those rare exceptional cases, GetAwaiter().GetResult()
will preserve the task exceptions,在那些罕见的异常情况下,
GetAwaiter().GetResult()
将保留任务异常,
If you use Wait
it will throw AggregateException.如果您使用
Wait
,它将抛出 AggregateException。
Refer to @stephen-cleary 's blog post 'a-tour-of-task-part-6-results'请参阅@stephen-cleary的博客文章“a-tour-of-task-part-6-results”
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.