Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between .RunSynchronously() and GetAwaiter().GetResult()?

I'm trying to run an asynchronous task synchronously and was wondering what the differences between .RunSynchronously() and GetAwaiter().GetResult() were.

I've seen a lot of comparisons between .Wait() and these two methods, but nothing comparing one with the other.

like image 921
DosCube Avatar asked Feb 22 '18 16:02

DosCube


People also ask

What is GetAwaiter () GetResult () in C#?

GetAwaiter(). GetResult()" is presented as a good way to replace ". Result" and ". Wait()" when we can't use async/await.

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.

Is Task run async or sync?

NET, Task. Run is used to asynchronously execute CPU-bound code.

Does Task run run synchronously?

Even though the task runs synchronously, the calling thread should still call Wait to handle any exceptions that the task might throw.


1 Answers

RunSyncronously indicates to run the delegate on the current thread with the current scheduler. However, this applies:

If the target scheduler does not support running this task on the calling thread, the task will be scheduled for execution on the scheduler, and the calling thread will block until the task has completed execution

Wait or GetAwaiter().GetResult() on the other hand doesn't schedule a Task at all, it simply blocks the calling thread until the task completes. This operation can deadlock if called from a single threaded synchronization context.

MSDN and Docs

like image 114
JSteward Avatar answered Sep 21 '22 09:09

JSteward