-1

Consider the following C# code:

var task1 = GetSomethingAsync();
var task2 = GetSomethingElseAsync();
await Task.WhenAll(task1, task2);  //is this required?
var something = await task1;
var somethingElse = await task2;

Does Task.WhenAll() make any difference for speed of execution (NOT for how any errors will be thrown)? If not, any reasons why I should have it anyway?

Update:

As a few people rightly pointed out, I should be using WhenAll() rather than WaitAll() - I've updated the question. But I'm still not clear on the answer - is there a reason to have WhenAll()? One of the answers here Why should I prefer single 'await Task.WhenAll' over multiple awaits? talks about fast-track async methods. If my async methods are fast-track, would it make a difference? I'm mainly concerned with the execution time, i.e. is it possible that without WhenAll() my two calls will execute sequentially. But also would be good to know if there are any other reasons to use WhenAll().

Andrew
  • 1,139
  • 1
  • 12
  • 27
  • you're mixing two different ways of doing things. you can only await in an async method. `Task.WaitAll` is more for blocking a thread until all tasks are completed. `await` will start a task and wait for the result, blocking until each is completed. so task2 won't even start until task1 is completed. – Joe_DM Sep 06 '20 at 05:18

1 Answers1

1

WaitAll, or the more modern WhenAll, will wait for both tasks to complete or fault.

var task1 = GetSomethingAsync(); // starts task
var task2 = GetSomethingElseAsync(); // starts task

var something = await task1; // wait until the first finishes
var somethingElse = await task2; // wait until the second finishes

Now, you just have a semantic problem.

You ask 2 friends to complete a task independently, you can

  • Wait for the first to come back then wait for the second to come back
  • Or wait for both to come back.

Either way you need to wait until both tasks are finished. WaitAll, WhenAll will not achieve anything differently in regards the speed it takes for the both tasks to finish (as they are already running independently) .

However, do note, there are other differences, though they are unrelated to speed

The exception to this would be if you had awaited the method directly

await GetSomethingAsync(); 
await GetSomethingElseAsync();

These lines execute in sequence, so you would add the time it takes to complete each task together.

And lastly, as noted by 41686d6564, WaitAny() and WhenAny() would only need to wait for the first task to finish (and not all), which can be desirable in some in situations.

TheGeneral
  • 79,002
  • 9
  • 103
  • 141