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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With