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.
GetAwaiter(). GetResult()" is presented as a good way to replace ". Result" and ". Wait()" when we can't use async/await.
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.
NET, Task. Run is used to asynchronously execute CPU-bound code.
Even though the task runs synchronously, the calling thread should still call Wait to handle any exceptions that the task might throw.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With