Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a difference between nesting multiple Task.WhenAll and flattening all tasks into one Task.WhenAll?

Sometimes I want to await a bunch of tasks in parallel but the tasks themselves depend on some condition. I could write

var tasks = new List<Task> { DoThisAsync(), DoThatAsync() };

if (condition) tasks.Add(AlsoDoOtherStuffAsync());

await Task.WhenAll(tasks);

But what if I write

var task = Task.WhenAll(DoThisAsync(), DoThatAsync());

if (condition) task = Task.WhenAll(task, AlsoDoOtherStuffAsync());

await task;

Is there any difference in behavior between the two versions? Is one preferred or mode idiomatic than the other?

like image 403
Kirill Rakhman Avatar asked Jan 22 '26 02:01

Kirill Rakhman


1 Answers

I think they are the same - HOWEVER I would recommend the first version over the second purely for readability/understandability - its to easy to mistakenly think AlsoDoOtherStuffAsync will only run after DoThisAsync() and DoThatAsync() have both completed in the second version, if you read it to casually, where as all three will actually all run in parallel.

like image 92
IRQ Conflict Avatar answered Jan 23 '26 15:01

IRQ Conflict



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!