C# Add Up Results of Async Methods When All Finished

后端 未结 1 1477
你的背包
你的背包 2021-01-29 01:35

I have an async method that gets a List of component ids for a car id. I want to get component ids for several hundred cars asynchronously, so I wrote t

相关标签:
1条回答
  • 2021-01-29 01:56

    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);
    
    0 讨论(0)
提交回复
热议问题