是 .GetAwaiter().GetResult();一般使用安全吗? [英] Is .GetAwaiter().GetResult(); safe for general use?
问题描述
我在几个地方读到 .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
?
推荐答案
正如我在我的博客中所描述的,GetAwaiter().GetResult()
在一次一个线程的上下文中使用时可能会死锁.这在 UI 线程上或在 ASP.NET 上下文中(对于核心 ASP.NET 之前)调用时最常见.
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屋!