Wait for a single Task in .NET C#: the Wait() method

Waiting for a single Task to finish is as easy as calling the Wait() method or one of its overloaded versions:

Wait();
Wait(CancellationToken);
Wait(int);
Wait(TimeSpan);
Wait(int, CancellationToken);

In short from top to bottom:

  • Wait until the Task completes, is cancelled or throws an exception
  • Wait until the cancellation token is cancelled or the task completes, is cancelled or throws an exception
  • Wait for ‘int’ amount of milliseconds to pass OR for the task to complete, be cancelled or throw an exception, whichever happens first
  • Wait for ‘TimeSpan’ amount of time to pass OR for the task to complete, be cancelled or throw an exception, whichever happens first
  • Wait for ‘int’ amount of milliseconds to pass, for the cancellation token to be cancelled, OR for the task to complete, be cancelled or throw an exception, whichever happens first

Example:

Construct the cancellation token:

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

Start a task:

Task task = Task.Factory.StartNew(() =>
{
	for (int i = 0; i < 10; i++)
	{
		cancellationToken.ThrowIfCancellationRequested();
		Console.WriteLine(i);
		cancellationToken.WaitHandle.WaitOne(1000);
	}
}, cancellationToken);

We can then wait for the task to complete:

task.Wait();

If we are impatient then we specify a maximum amount of milliseconds for the task to complete otherwise it is abandoned:

task.Wait(2000);

The other overloads work in a similar manner.

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

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

One Response to Wait for a single Task in .NET C#: the Wait() method

  1. Pingback: Wait for a single Task in .NET C#: the Wait() method | D Says

Leave a comment

Elliot Balynn's Blog

A directory of wonderful thoughts

Software Engineering

Web development

Disparate Opinions

Various tidbits

chsakell's Blog

WEB APPLICATION DEVELOPMENT TUTORIALS WITH OPEN-SOURCE PROJECTS

Once Upon a Camayoc

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