How to use Task.WhenAll () for multiple lists of different return types?

I have two sets of Tasks, each with a different type of result:

IEnumerable<Task<T1>> set1 = GetTasksOfT1();
IEnumerable<Task<T2>> set2 = GetTasksOfT2();

Now I would like to wait for both sets on the same line, but I had to design set1 with cast:

 await Task.WhenAll(set1.Select(p => p as Task).Concat(set2));

This is because I get this error if I do not use casting:

IEnumerable<Task<T1>>' does not contain a definition for 'Concat' 
and the best extension method overload 'Queryable.Concat<Task<T2>>(IQueryable<Task<T2>>, IEnumerable<Task<T2>>)' 
requires a receiver of type 'IQueryable<Task<T2>>'

It is obvious.

So, is there a way to use single WhenAll () without casting?

Edit: The inverse types T1 and T2 are important - I consume them after the expected tasks:

//After await Task.WhenAll(...):
var t1Results = await set1; // all set1 Tasks are completed by now 
var t2Results = await set2; // same
DoSomethingWithResults(t1Results, t2Results);
+4
source share
4 answers

Actually, the compiler simply complains about the failure of type inference. You can help with this:

IEnumerable<Task<int>> set1 = null;
IEnumerable<Task<string>> set2 = null;

set1.Concat((IEnumerable<Task>)set2); //#1
((IEnumerable<Task>)set1).Concat(set2); //#2
set1.Concat<Task>(set2); //#3

. , IEnumerable . Enumerable.Concat<Task>(IEnumerable<Task>, IEnumerable<Task>).

+2

, GetTasksOfT1 GetTasksOfT2 Task<T>, Task, .

, Task, IEnumerable<Task> Kote.

+1

Task s, .

, ( usr) :

IEnumerable<Task<T1>> set1 = GetTasksOfT1();
IEnumerable<Task<T2>> set2 = GetTasksOfT2();

await Task.WhenAll(set1.Concat<Task>(set2));

var t1Results = await Task.WhenAll(set1);
var t2Results = await Task.WhenAll(set2);

Bu , await . , - , await s.

0

Although to be controversial, if creating an array is better than combining two enumerated elements, you can leave the concatenation from the equation:

await Task.WhenAll(set1, set2);

But, since what you need is the result of evaluating each sequence of tasks, I would not wait for them all as one set:

DoSomethingWithResults(await set1, await set2);
0
source

Source: https://habr.com/ru/post/1625696/


All Articles