Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is .GetAwaiter().GetResult(); safe for general use?

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?

like image 985
Cyan Avatar asked Aug 17 '16 22:08

Cyan


People also ask

Is it safe to use GetAwaiter () GetResult ()?

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 has the same problems. The appropriate fix is to use await , and make the calling code asynchronous.

How do you use GetAwaiter?

When you write “ await task; ”, the compiler translates that into usage of the Task. GetAwaiter() method, which returns an instance that has a GetResult() method. When used on a faulted Task, GetResult() will propagate the original exception (this is how “ await task; ” gets its behavior). You can thus use “ task.


1 Answers

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 has the same problems. The appropriate fix is to use await, and make the calling code asynchronous.

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.

like image 90
Stephen Cleary Avatar answered Sep 18 '22 23:09

Stephen Cleary