是.GetAwaiter().GetResult();可以安全使用吗? [英] Is .GetAwaiter().GetResult(); safe for general use?

查看:105
本文介绍了是.GetAwaiter().GetResult();可以安全使用吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在一些地方读到.GetAwaiter().GetResult();可能导致死锁,我们应该改用async/await.但是我看到许多使用此代码的代码示例.可以使用吗?它在哪些情况下可能会死锁?还有其他我应该使用的东西,例如Task.Wait?

I read in a few places that .GetAwaiter().GetResult(); could cause deadlocks and that we should use async/await instead. But I see many code samples where this is used. Is it ok to use it? Which are the cases where it can deadlock? Is there something else I should use, like Task.Wait?

推荐答案

正如我在博客中所述,

As I describe on my blog, GetAwaiter().GetResult() can deadlock when it's used in a one-thread-at-a-time context. This is most commonly seen when called on the UI thread or in an ASP.NET context (for pre-Core ASP.NET).

Wait具有相同的问题.适当的解决方法是使用await,并使调用代码异步.

Wait has the same problems. The appropriate fix is to use await, and make the calling code asynchronous.

请注意,控制台应用程序中的Main方法是该规则的例外;在那里使用是非常合适的.许多代码示例都以这种方式使用它.

Note that the Main method in Console apps is an exception to this rule; it is perfectly appropriate to use there. Many code samples use it in this way.

这篇关于是.GetAwaiter().GetResult();可以安全使用吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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