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

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

问题描述

我正在尝试为我的一个项目找到最佳实践.这是一个典型的 WPF 应用程序,其 UI 显示项目列表,并且有一个返回结果的数据服务.

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.我们面前有两个选择:

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

  1. 使用异步等待关键字这需要将所有方法标记为 Async 从按钮单击一直到服务层(客户端的类,用于对服务器进行 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和callback在这种方法中,UI 客户端调用服务层并将回调传递给服务层,服务层将向服务器的 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(async() =>//等待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

推荐答案

你应该一直使用 asyncawait 关键字,否则你不应该使用完全异步.

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.

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

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