Monday 28 November 2016

.Net High Performance Part 6 : Task Cancellation in TPL

When we are using the TPL , there are situations where we need to cancel a Task in the middle of its execution. We can use the CancellationTokenSource to perform this operation with a shared token.

Following is the code snippet about how we can achieve this.

private CancellationTokenSource mCancelTokenSource;
private List<Task> mRunningTasks;

private CancellationTokenSource m_cts;

// Any Constructor or a Main method

void Main()
{
   mCancelTokenSource= new CancellationTokenSource();
   mRunningTasks= new List<Task>();
}

// Any event that trigger the Task

CancellationToken token = m_cts.Token;

Task<string> T = new Task<string>(() =>
{
// code for the Task which returns a string

return result;
},

token  // rhe cancellation token:
);

mRunningTasks.Add(T);
T.Start();

// any event that handles the cancellation

mCancelTokenSource.Cancel();

// If we need to create new tasks and cancel them too
mCancelTokenSource =  new CancellationTokenSource();

We need to pay special attention to the exception handling when canceling a task. Upon cancellation , the task would throw the OperationCanceledException Hence , we need to ignore this particular exception inside our catch block.

try
{
       
}

catch(AggregateException ae)
{
     ae = ae.Flatten();

    foreach(var ex in ae.InnerExceptions)
    {
        if(  ex is  OperationCanceledException )
            // ignore this exception ;
        else
           // handles the exception
     }
}


No comments:

Post a Comment