问题描述
我有一个异步方法,该方法获取汽车ID的组件ID的List<long>
.我想异步获取数百辆汽车的组件ID,因此我在下面编写了方法.我的目标是实际上将所有GetAllComponentIdsForCar
任务的结果加起来,并从下面的方法中返回它们.
I have an async method that gets a List<long>
of component ids for a car id. I want to get component ids for several hundred cars asynchronously, so I wrote the method below. My goal is to actually add up the results of all GetAllComponentIdsForCar
tasks, and return them from the method below.
public async Task<List<long>> GetListOfComponentIds(List<long> carIds)
{
List<Task> tasksList = new List<Task>();
foreach (var carId in carIds)
{
Task<List<long>> getComponentIds = GetAllComponentIdsForCar(carId);
tasksList.Add(getComponentIds);
}
await Task.WhenAll(tasksList);
//List<long> sumOfAllTaskResults...or array...or something
}
我如何做到这一点?
注意-我正在寻找类似于angular的 q.all 仅在完成后返回所有任务(/承诺)结果的数组.
Note - I am looking for something similar to angular's q.all which simply returns an array of all the task(/promise) results when finished.
以前,我已经设法从C#中的异步任务中获取结果,但是这涉及到使数组具有预期任务的长度,这似乎是一种可怕的方法.
I have managed to get results from async tasks in C# before, but that involved making an array the length of expected tasks and that just seems like a horrible way to do it.
我确实尝试在这里阅读Microsoft的文档和问题,但是我所看到的只是关于WaitAll与WhenAll的争论.
I did try reading Microsoft's documentation and questions here, but all I see are arguments about WaitAll vs WhenAll.
推荐答案
如果将taskList
的声明更改为使用Task
的通用版本,则Task<T>
表示类型为T
的将来值. ..
If you changed the declaration of taskList
to use the generic version of Task
, Task<T>
that represents a future value of type T
...
List<Task<List<long>>> taskList
现在任务的结果是List<long>
类型,而不是void
类型,编译器类型推断将使您切换到Task.WhenAll
的不同重载, Task.WhenAll<TResult>(Task<TResult> tasks)
.
now the task's result is of type List<long>
rather than void
, and compiler type inference will switch you to a different overload of Task.WhenAll
, Task.WhenAll<TResult>(Task<TResult> tasks)
.
[...]
返回任务的Task<TResult>.Result
属性将被设置为一个数组,该数组包含所提供任务的所有结果,其顺序与提供时所提供的顺序相同(例如,如果输入任务数组包含t1, t2, t3
,则输出任务的结果Task<TResult>.Result
属性将返回TResult[]
,其中arr[0] == t1.Result, arr[1] == t2.Result
和arr[2] == t3.Result
).
The Task<TResult>.Result
property of the returned task will be set to an array containing all of the results of the supplied tasks in the same order as they were provided (e.g. if the input tasks array contained t1, t2, t3
, the output task's Task<TResult>.Result
property will return an TResult[]
where arr[0] == t1.Result, arr[1] == t2.Result
, and arr[2] == t3.Result
).
因此,由于Task
的类型为List<long>
,因此以下语句是您访问整理结果数组的方式:
so, as the type of Task
is List<long>
, the following statement is how you'd access the collated result array:
List<Long>[] resultLists = await Task.WhenAll(tasksList);
这篇关于全部完成后,C#将异步方法的结果加起来的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!