Waiting for a group of Tasks to complete in .NET C#

You can use the static WaitAll() method to wait for more than one task to complete. If you use the WaitAll(tasks[]) version then WaitAll only returns if all tasks in the task array have completed.

WaitAll() has a number of overloaded versions which follow the same pattern as the Wait() method we saw in this post.


Build the cancellation token:

CancellationTokenSource cancellationTokenSource = new CancellationTokenSource();
CancellationToken cancellationToken = cancellationTokenSource.Token;

Construct two – or more- tasks:

Task taskOne = Task.Factory.StartNew(() =>
	for (int i = 0; i < 10; i++)
	Console.WriteLine("Task 1 complete");
}, cancellationToken);

Task taskTwo = Task.Factory.StartNew(() =>
	for (int i = 0; i < 5; i++)
	Console.WriteLine("Task 2 complete");
}, cancellationToken);

Wait for them:

Task.WaitAll(taskOne, taskTwo);

Note that a task provided to the WaitAll method is considered “complete” if either of the following is true:

  • The task finishes its work
  • The task is cancelled
  • The task has thrown an exception

If one of the tasks throws an exception then WaitAll will also throw one.

View the list of posts on the Task Parallel Library here.

About Andras Nemes
I'm a .NET/Java developer living and working in Stockholm, Sweden.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

Elliot Balynn's Blog

A directory of wonderful thoughts

Software Engineering

Web development

Disparate Opinions

Various tidbits

chsakell's Blog


Once Upon a Camayoc

Bite-size insight on Cyber Security for the not too technical.

%d bloggers like this: