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:
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
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
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.
C# Language Async-Await Async/await will only improve performance if it allows the machine to do additional work.
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.
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.
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.
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