gpt4 book ai didi

c# - 如何在 C# 中选择异步调用的方法,如何传播异步

转载 作者:太空狗 更新时间:2023-10-30 00:10:27 25 4
gpt4 key购买 nike

我很少使用异步方式来编写程序问题。我正在使用一些昂贵的方法编写 WCF 服务,这些方法非常适合异步调用。但我对实现的问题是:

  1. 如果我要在模型中创建异步方法,那么我需要将服务方法标记为异步以便能够等待模型方法,并将返回类型更改为 Task<originalType> .这将破坏服务 API 约定的一致性。正确的做法是什么?服务接口(interface)设计成async Task是不是更好返回方法,即使某些方法并不昂贵并且实际上没有理由使其异步?
  2. 据我所知,只有昂贵的方法才应该写成异步的,但在这种情况下,程序的一半将是同步的,而另一半是异步的。对吗?

最佳答案

If I will create async method in the model, then I need mark service method as async to be able to await the model method, and change the return type to Task. This will destroy service api convention consistency. What is the right way to go? Is it better to design the service interface as async Task returning methods even if some methods are not expensive and there is practically no reason to make it asnyc?

在 WCF 中,当您更改方法以返回 Task<T> 时,您实际上并没有更改 WCF 契约(Contract),因为它可以识别单个消息的多个异步模式,这意味着您可以在单个契约(Contract)界面中拥有所有 3 种模式(任务、同步和 APM),它们都将与同样的信息。

来自 MSDN :

Clients can offer the developer any programming model they choose, so long as the underlying message exchange pattern is observed. So, too, can services implement operations in any manner, so long as the specified message pattern is observed.

此主题涵盖在 Different forms of the WCF service contract interface 中进行扩展和 Asynchronously consume synchronous WCF service

As I understood, only expensive method should be written as async, but in such case one half of the program will bee synchronous and the second one asynchronous. Is it right?

正如@l3arnon 所说,暴露一个 async api 不是关于方法有多“昂贵”,而是关于方法调用正在做的工作。如果它是真正的异步工作,例如访问文件系统、发送网络请求、访问外部数据源(例如数据库),那么它是公开异步 api 的合适人选。

将这些事实与 WCF 相结合,您可以通过单个契约公开同步和异步方法。

关于c# - 如何在 C# 中选择异步调用的方法,如何传播异步,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24379071/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com