Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between .Wait() vs .GetAwaiter().GetResult()?

People also ask

What is GetAwaiter () GetResult ()?

GetAwaiter(). GetResult()", ". Result" or ". Wait()" to get the result of a task or to wait for the task completion you may experience deadlocks or thread pool starvation.

What is the use of GetAwaiter in C#?

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. GetAwaiter().

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

@Cyan: Yes, any kind of ASP.NET request context. Pre-Core, that is; the request context was removed in ASP.NET Core. "Main method in Console apps is an exception to this rule; it is perfectly appropriate to use there.

What does Task run do C#?

The Run method allows you to create and execute a task in a single method call and is a simpler alternative to the StartNew method. It creates a task with the following default values: Its cancellation token is CancellationToken.


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

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. 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".

An example of how this works is in the reference source (non-contractual, of course).