Naeem Sarfraz
Naeem Sarfraz

Reputation: 7430

Awaiting tasks of different types

IEnumerable<Task<Request>> requestTasks = CreateRequestTasks();
Task<Trace> traceTask = CreateTraceTask();

var tasks = new List<Task>();
tasks.AddRange(requestTasks);
tasks.Add(traceTask);

await Task.WhenAll(tasks);

How do I get the result from the requestTasks collection?

Upvotes: 4

Views: 2351

Answers (2)

user6996876
user6996876

Reputation:

Since you have to await them all, you can simply write

IEnumerable<Task<Request>> requestTasks = CreateRequestTasks();
Task<Trace> traceTask = CreateTraceTask();

var tasks = await Task.WhenAll(requestTasks);
var trace = await traceTask;

inside an equivalent async block: it may look clearer imho.

Notice also that the above traceTask starts on create (actually this is the same answer since the question itself is a duplicate).

Upvotes: 2

Stephen Cleary
Stephen Cleary

Reputation: 456527

How do I get the result from the requestTasks collection?

Keep it as a separate (reified) collection:

List<Task<Request>> requestTasks = CreateRequestTasks().ToList();
...
await Task.WhenAll(tasks);
var results = await Task.WhenAll(requestTasks);

Note that the second await Task.WhenAll won't actually do any "asynchronous waiting", because all those tasks are already completed.

Upvotes: 11

Related Questions