异步等待VS GetAwaiter()调用getResult()和回调 [英] Async await vs GetAwaiter().GetResult() and callback

查看:2661
本文介绍了异步等待VS GetAwaiter()调用getResult()和回调的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图找到我的项目的一个最好的做法。它是一种典型的WPF应用程序与用于显示项目的列表并有一个返回的结果的数据服务的用户界面。

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.

我们是异步调用服务,以便不阻塞UI。我们已经在我们面前2个选项:

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


  1. 使用异步等待关键字
    这需要标记的所有方法异步从点击链接一路(使HTTP调用在服务器类上的客户端)的服务层和其间的任何方法。这种方法适用罚款等随处可见,然后异步传播的问题,

  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

使用awaiter和回调
在这种方法中,用户界面​​客户端调用服务层,并传递一个回调到服务层,服务层包装了HTTP调用服务器在任务和使用GetAwaiter()调用getResult(),当HTTP通话结束后它会调用由UI客户端传递回调。在这种情况下,没有任何方法有明显的异步,但不能确定对使用GetAwaiter的()

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(异步()=> //等待HTTP调用,调用回调函数).GetAwaiter()调用getResult();

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.

您第二个选项是不是真的异步的。它调用的异步操作,以同步阻止它task.GetAwaiter()调用getResult()
对存在非常复杂的它不是异步的,并可能导致死锁。顶部

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.

这篇关于异步等待VS GetAwaiter()调用getResult()和回调的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆