异步等待如何使用返回值 [英] Async await how to use return values
问题描述
我有一个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> " + 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;
这篇关于异步等待如何使用返回值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!