Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Task.WhenAll return list instead of array

I try to find a solution of this but I didn't able to find it. That's why I'm asking here. :)

I'm having a list of tasks and It has two items

List<Task<int>> tasks = new List<Task<int>>();
     tasks.Add(Task.FromResult(1));
          tasks.Add(Task.FromResult(2));

When I call await Task.WhenAll(tasks), it returns int[] but I want it should return List<int>. Like below:

List<int> result = await Task.WhenAll(tasks);

I want to add new item in the list after I've the result.

like image 395
Saadi Avatar asked Jan 10 '17 06:01

Saadi


People also ask

What does WhenAll return?

WhenAll can run a bunch of async methods in parallel and returns when every one finished.

Can you tell difference between task WhenAll and task WhenAny?

WhenAll returns control after all tasks are completed, while WhenAny returns control as soon as a single task is completed.

Is task WhenAll sequential?

WhenAll reifies your task sequence so it knows how many tasks it needs to wait for.

Does task WhenAll start the tasks?

WhenAll starts both Tasks at the same time and executes them in parallel, the outcome is that instead of taking 3 seconds to run the program it just takes 2 seconds, that's a huge performance enhancement!


1 Answers

You can write:

List<int> result = (await Task.WhenAll(tasks)).ToList();

This will convert the array to a list.

Do not forget to add the namespace:

using System.Linq;
like image 100
Peter Avatar answered Oct 15 '22 08:10

Peter