Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between await and GetAwaiter() in C# [duplicate]

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 212
vikas mittal Avatar asked Nov 18 '22 08:11

vikas mittal


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 168
i3arnon Avatar answered Dec 04 '22 02:12

i3arnon