BlackWaspTM

This web site uses cookies. By using the site you accept the cookie policy.This message is for compliance with the UK ICO law.

Parallel and Asynchronous
.NET 4.0+

Task Cancellation

The fourteenth part of the Parallel Programming in .NET tutorial examines how parallel tasks are cancelled. This includes stopping single tasks, co-ordinating the cancellation of multiple tasks and dealing with tasks that are cancelled before they start.

Cancelling Multiple Tasks

In many situations you will launch multiple parallel tasks. When cancellation is required you may want to cancel a group of tasks, rather than just one. This is achieved by using the same token for each task in the group. We can see this in the following example. Here two tasks are started and both are cancelled with a single call to the token source's Cancel method.

static void Main()
{
    var tokenSource = new CancellationTokenSource();
    var token = tokenSource.Token;
    var task = new Task(() => DoLongRunningTask(token), token);
    var task2 = new Task(() => DoLongRunningTask(token), token);

    Console.WriteLine("Press Enter to cancel");
    task.Start();
    task2.Start();

    Console.ReadLine();
    tokenSource.Cancel();

    try
    {
        Task.WaitAll(task, task2);
    }
    catch (AggregateException ex)
    {
        ex.Handle(e =>
        {
            return e is OperationCanceledException;
        });
    }

    task.Dispose();
    task2.Dispose();
    Console.ReadLine();
}

NB: If you have several groups of tasks that can be cancelled, use a separate CancellationTokenSource to generate tokens for each group.

26 November 2011