Freigeben über


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.

Comments

  • Anonymous
    January 02, 2008
    PingBack from http://msdnrss.thecoderblogs.com/2008/01/02/how-to-cancel-a-task-in-parallel-fx/

  • Anonymous
    February 22, 2008
    I'm curious how you know that IsCancelled is volatile. It doesn't show up as volatile in Reflector, but maybe Reflector doesn't indicate that. Bob

  • Anonymous
    February 23, 2008
    It is not the IsCanceled property which is volatile (properties are methods and cannot be volatile). It is the m_canceled field used by this property which is volatile. HTH, Pedram