Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get result from Task.WhenAll

Tags:

I have multiple tasks returning the same object type that I want to call using Task.WhenAll(new[]{t1,t2,t3}); and read the results.

When I try using

Task<List<string>> all = await Task.WhenAll(new Task[] { t, t2 }).ConfigureAwait(false);

I get a compiler error

Cannot implicitly convert type 'void' to 'System.Threading.Tasks.Task<System.Collections.Generic.List<string>>

both tasks are calling method similar the this.

private Task<List<string>> GetFiles(string path)
{
    files = new List<string>();
    return  Task.Run(() =>
    {
       //remove for brevity 
        return files;
    });
}
like image 556
user3373870 Avatar asked Jul 22 '15 04:07

user3373870


People also ask

What does WhenAll return?

public static Task WhenAll (params Task[] tasks); Task. WhenAll creates a task that will complete when all of the supplied tasks have been completed. It's pretty straightforward what this method does, it simply receives a list of Tasks and returns a Task when all of the received Tasks completes.

What is the use of task WhenAll?

WhenAll(Task[])Creates a task that will complete when all of the Task objects in an array have completed.

How do I return a task in C#?

The recommended return type of an asynchronous method in C# is Task. You should return Task<T> if you would like to write an asynchronous method that returns a value. If you would like to write an event handler, you can return void instead. Until C# 7.0 an asynchronous method could return Task, Task<T>, or void.

What is the difference between task WaitAll and task WhenAll?

The Task. WaitAll blocks the current thread until all other tasks have completed execution. The Task. WhenAll method is used to create a task that will complete if and only if all the other tasks have completed.


2 Answers

Looks like you are using the overload of WaitAll() that doesn't return a value. If you make the following changes, it should work.

List<string>[] all = await Task.WhenAll(new Task<List<string>>[] { t, t2 })
                               .ConfigureAwait(false);
like image 175
Mike Hixson Avatar answered Sep 20 '22 07:09

Mike Hixson


The return type of WhenAll is a task whose result type is an array of the individual tasks' result type, in your case Task<List<string>[]>

When used in an await expression, the task will be "unwrapped" into its result type, meaning that the type of your "all" variable should be List<string>[]

like image 44
Jonas Høgh Avatar answered Sep 20 '22 07:09

Jonas Høgh