Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Async await vs GetAwaiter().GetResult() and callback

I am trying to find the best practice for one of my project. It is a typical WPF application with a UI that displays a list of items and there is a data service that returns the result.

We are calling the service asynchronously so as to not block the UI. We have 2 options in front of us:

  1. Using Async await keywords This requires marking all the methods Async from button click all the way to service layer (class on client side that makes the http call to the server) and any method in between. This approach works fine other then the issue of propagating async everywhere

  2. Use awaiter and callback In this approach the UI client calls the service layer and passes a callback to the service layer, the service layer wraps the http call to the server in a task and use GetAwaiter().GetResult(), when the http call is finished it invokes the callback passed by the UI client. In this case no method has to marked async, but not really sure about the use of GetAwaiter()

    Task.Run(async () => //await http call, invoke callback).GetAwaiter().GetResult();

I am just trying to find out which is a better approach and if there are some issues with either approach that I should be aware of

like image 449
vikas mittal Avatar asked Dec 31 '15 17:12

vikas mittal


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.

Does async await improve performance?

C# Language Async-Await Async/await will only improve performance if it allows the machine to do additional work.

Is .result same as await?

await asynchronously unwraps the result of your task, whereas just using Result would block until the task had completed. See this explanantion from Jon Skeet.

What is a GetAwaiter?

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

You should use the async and await keywords all the way up, or you shouldn't use async at all.

Your second option is not really asynchronous. It's calling an asynchronous operation and blocking on it synchronously with task.GetAwaiter().GetResult(). On top of being very complicated it's not asynchronous and may lead to deadlocks.

like image 90
i3arnon Avatar answered Oct 09 '22 09:10

i3arnon