22

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;
    });
}
Alexei Levenkov
  • 98,904
  • 14
  • 127
  • 179
user3373870
  • 1,406
  • 2
  • 13
  • 17
  • Can you please clarify what part of MSDN sample for [WhenAll](https://msdn.microsoft.com/en-us/library/hh194766%28v=vs.110%29.aspx) is not clear? Would make question easier to answer. – Alexei Levenkov Jul 22 '15 at 04:58
  • 1
    Actually none of the article is not clear. What is not clear is where this void is coming from. – user3373870 Jul 22 '15 at 05:13
  • I see - as Mike Hixson pointed out you have list of `Task` (task that does not return value) instead of `Task` - hence await results in `void`. Normally you just not specify type by using shortcut array syntax to avoid such issues - `ask.WhenAll(new[] { t, t2 })...`. or use properly typed list/array of tasks as shown in MSDN sample - `var tasks = new List>();`. – Alexei Levenkov Jul 22 '15 at 05:20
  • ^ This is the real answer. – mwilson Jan 17 '20 at 21:13

2 Answers2

16

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);
Quality Catalyst
  • 6,531
  • 8
  • 38
  • 62
Mike Hixson
  • 5,071
  • 1
  • 19
  • 24
4

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>[]

Jonas Høgh
  • 10,358
  • 1
  • 26
  • 46