How to cancel a task in Parallel FX?

Task Parallel Library (TPL) allows you to easily cancel tasks. Effectively you need to call the Cancel method on the task in question. Imagine the simple sample below:

Task task1 = Task.Create(Foo, 10000);

static void Foo(object o)

{

  for (int i = 0; i < (int)o; i++)

  {

    // some code here

  }

}

A task is created and Foo is automatically called. At some point if you decide to cancel the task while it is running, you can call the Cancel method on the task as shown below:

Task task = Task.Create(Foo, 10000);

task.Cancel();

When you call cancel, all you are doing is to set a Boolean field to true. You can query its value through the IsCanceled property:

task.IsCanceled

When Cancel is called, if the task has not yet prepared for execution, it will not run. However if the task has already been prepared and assigned to a thread, it will start executing. The execution is not automatically interrupted and requires manual intervention in order to cancel. Effectively you need to build the cancelation logic into your application:

static void Foo(object o)

{

  for (int i = 0; i < (int)o; i++)

  {

    // Could it have been cancelled?

    ThrowIfCurrentTaskCanceled();

    // some code here

  }

}

internal static void ThrowIfCurrentTaskCanceled()

{

  Task current = Task.Current;

  if (current != null && current.IsCanceled)

  {

    throw new TaskCanceledException(current);

  }

}

As you can see, it is possible to access the current Task and check to see if it has already been cancelled. One thing to remember regarding the Boolean field used by the IsCanceled property is that it is a volatile field meaning that all reads are volatile reads and have acquire semantics which can be expensive.

On a slightly different note, if you are unsure about the spelling of “Cancelled” then take a look at this post.