gpt4 book ai didi

c# - 在使用 await 的 WCF 方法中返回一个项目

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

我正在使用 WCF 创建 RESTful Web 服务。考虑以下服务契约(Contract)和实现:

[ServiceContract]
public interface IItemsSaleService
{
[OperationContract]
[WebInvoke(Method = "GET", ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Wrapped, UriTemplate = "getItemDetails/{itemId}")]
SaleItem GetItemDetails(string itemId); //GET
}

//IMPLEMENTATION

async public SaleItem GetItemDetails(string itemId) //This wont work. It should be Task<SaleItem>
{

SaleItem item = await FindItem(itemId);
return item;
}

假设 FindItem 是第三方 API 方法。由于我正在使用 await,GetItemDetails 方法必须标记为异步,因此不能返回 SaleItem。它必须返回 void 或一个对我不起作用的任务,因为该方法必须返回 SaleItem 以便序列化程序将其转换为 JSON 并将其返回给客户端。

我该如何解决这个问题?

另一个相关问题:

方法 A 调用方法 B 调用方法 C - 方法 C 使用 await。这是否自动要求所有其他方法都是异步的,因此总是返回 Task<> 或 void?

最佳答案

Assume that the FindItem is a thirdparty API method. Since I am using await, the method GetItemDetails has to be marked async and hence cannot return SaleItem. It has to return void or a Task which wont work for me as the method HAS to return SaleItem for the serializer to convert it to JSON and return it back to the client.

它会起作用的。来自 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.

这意味着 WCF 可以在单个消息的同步和异步模式之间切换。 Noseratios 链接中提供了广泛的答案:Different forms of the WCF service contract interface

Method A calls Method B calls Method C - Method C uses await. Does this automatically require all the other methods to be async and hence always return Task<> or void?

异步方法本质上会一直向上传播。使用 await 的方法关键字必须标记其方法 async返回类型为 Task , Task<T> , 或 void .通知 void返回 async方法仅用于异步事件处理程序的兼容性,不应在该范围之外使用。

制作你的方法时有案例async不是必需的,只需返回内部调用的 Task就足够了,您可以在这里阅读更多相关信息:Any difference between "await Task.Run(); return;" and "return Task.Run()"?

关于c# - 在使用 await 的 WCF 方法中返回一个项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24158279/

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