VSO
VSO

Reputation: 12646

C# Add Up Results of Async Methods When All Finished

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
}

How do I accomplish this?

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.

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.

I did try reading Microsoft's documentation and questions here, but all I see are arguments about WaitAll vs WhenAll.

Edit:

enter image description here

Upvotes: 2

Views: 2559

Answers (1)

spender
spender

Reputation: 120498

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

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).

Creates a task that will complete when all of the Task objects in an enumerable collection have completed

[...]

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).

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);

Upvotes: 4

Related Questions