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);
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:
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:
// Could it have been cancelled?
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.
PingBack from http://msdnrss.thecoderblogs.com/2008/01/02/how-to-cancel-a-task-in-parallel-fx/
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.
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.