Erik Kinding
Erik Kinding

Reputation: 1870

Does await Task.WhenAll in C# .NET block?

I'm a bit confused when it comes to the async/await stuff in .NET...

Consider the following method:

public async Task DoSomething() {
   IEnumerable<Task> ts = GetSomeTasks(); // Some tasks that would do some random IO stuff, or whatever
   await Task.WhenAll(ts);
   Console.WriteLine("All tasks completed!");
}

Is the call to Console.WriteLine guaranteed to be executed after the tasks in ts have been awaited? I think I've seen cases where await doesn't seem to "block" like that until the task result is accessed. What rules apply?

Upvotes: 2

Views: 1556

Answers (3)

Jon Skeet
Jon Skeet

Reputation: 1500595

Is the call to Console.WriteLine guaranteed to be executed after the tasks in ts have been awaited?

Yes.

I think I've seen cases where await doesn't seem to "block" like that until the task result is accessed.

No, that's not the case. You'll only get to the statement after the await operator (or potentially the next expression within a statement, e.g. for (await a) + (await b) once the thing that's being awaited has completed.

Note that Task.WhenAll is not a blocking method in itself (unlike Task.WaitAll) - but it returns a task that does not complete until all the tasks passed as arguments have completed.

Upvotes: 7

Zohar Peled
Zohar Peled

Reputation: 82474

From Task.WhenAll Method documentation:

Creates a task that will complete when all of the supplied tasks have completed.

The first example on this page has the following text:

The following example creates a set of tasks that ping the URLs in an array. The tasks are stored in a List collection that is passed to the WhenAll(IEnumerable) method. After the call to the Wait method ensures that all threads have completed....

This means that the answer to your question is Yes - The call to Console.WriteLine will happen only after all the tasks have completed.

Upvotes: 4

Yes - you are guaranteed that Console.WriteLine is executed after all tasks in ts have completed because you await it. This is documented here: https://learn.microsoft.com/en-us/dotnet/api/system.threading.tasks.task.whenall?view=netframework-4.8

Upvotes: 2

Related Questions