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