Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Awaiting tasks of different types

Tags:

c#

async-await

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?

like image 210
Naeem Sarfraz Avatar asked Oct 17 '25 03:10

Naeem Sarfraz


2 Answers

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.

like image 144
Stephen Cleary Avatar answered Oct 19 '25 15:10

Stephen Cleary


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).


Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!