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.

Example:

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++)
	{
		cancellationToken.ThrowIfCancellationRequested();
		Console.WriteLine(i);
		cancellationToken.WaitHandle.WaitOne(1000);
	}
	Console.WriteLine("Task 1 complete");
}, cancellationToken);

Task taskTwo = Task.Factory.StartNew(() =>
{
	for (int i = 0; i < 5; i++)
	{
		cancellationToken.ThrowIfCancellationRequested();
		Console.WriteLine(i);
		cancellationToken.WaitHandle.WaitOne(500);
	}
	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.

Advertisements

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 )

Google photo

You are commenting using your Google 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

ultimatemindsettoday

A great WordPress.com site

Elliot Balynn's Blog

A directory of wonderful thoughts

Softwarearchitektur in der Praxis

Wissenswertes zu Webentwicklung, Domain-Driven Design und Microservices

Technology Talks

on Microsoft technologies, Web, Android and others

Software Engineering

Web development

Disparate Opinions

Various tidbits

chsakell's Blog

WEB APPLICATION DEVELOPMENT BEST PRACTICES WITH MICROSOFT STACK & ANGULAR

Cyber Matters

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

Guru N Guns's

OneSolution To dOTnET.

Johnny Zraiby

Measuring programming progress by lines of code is like measuring aircraft building progress by weight.

%d bloggers like this: