Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.7k views
in Technique[技术] by (71.8m points)

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...