异步等待如何使用返回值

编程入门 行业动态 更新时间:2024-10-19 21:31:26
本文介绍了异步等待如何使用返回值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有一个Windows服务,该服务是从另一个开发人员继承的,它运行非常缓慢,并且对eBay API的调用速度很慢.我希望在不进行过多重构的情况下加快速度.

I have a windows service that I have inherited from another developer, it runs very slow and has numerous slow call to the eBay API. I wish to speed it up without too much refactoring.

我刚刚开始研究使用c#async/await尝试获取一些运行异步的慢速调用. 这是我想要实现的目标:

I've just started to look at using c# async/await to try to get some of these slow call to run async. Here's what i'm trying to achieve:

我有一个非常繁忙的方法,它会发出很多呼叫,如下所示:

I have a 1 very busy method that makes lots of calls as below:

getProducts getCategories getVehicles getImages

我的想法是,我可以简单地将方法更改为async并将Task<T>添加到返回类型,如下所示:

My thoughts were that I could simply change the methods to async and add Task<T> to the return type as below:

public async Task<String> ProcessAdditionalProductDetialsAsync(ItemType oItem) { String additionalProductDetails = string.Empty; if (oItem.ItemSpecifics.Count > 0) { foreach (NameValueListType nvl in oItem.ItemSpecifics) { if (nvl.Value.Count > 0) { foreach (string s in nvl.Value) { additionalProductDetails += "<li><strong>" + nvl.Name + ":</strong>&nbsp;" + s + "</li>"; } } } } return additionalProductDetails; }

然后致电等待他们:

Task<String> additionalProductDetials = ebayPartNumbers.ProcessAdditionalProductDetialsAsync(item); Task<PartNumberCollection> partNumberCollection = ebayPartNumbers.ProcessPartNumbersAsync(item); await Task.WhenAll(partNumberCollection, additionalProductDetials);

如何掌握返回的类型,以便可以使用它们?我已经尝试过仅使用partNumberCollection,但是它仅具有await属性.

How do I get hold of the returned types so I can use them? I have tried just using partNumberCollection but it only has the await properties available.

推荐答案

使用结果属性:

await Task.WhenAll(partNumberCollection, additionalProductDetials); var partNumberCollectionResult = partNumberCollection.Result; var additionalProductDetialsResult = additionalProductDetials.Result;

更多推荐

异步等待如何使用返回值

本文发布于:2023-11-08 20:27:32,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1570374.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:如何使用   返回值

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!