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?

1 answer

  • answered 2018-10-23 09:57 IRQ Conflict

    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.