Cancelling a task

1. Why do we need the method which throws the exception to cancel a task?

2. Will a task start if it had been canceled before it was scheduled?

3. How to get access to CancellationToken which was used to create the task?

To distinguish the way a task terminated we should throw the OperationCanceledException otherwise we can get corrupted data.

If the CancellationToken get canceled before the task is scheduled, the task gets canceled and never executes at all.

To get access to the CancellationToken which was used to create the task we can use a lambda expression and “pass” the CancellationToken as a closure variable.

Sample 1:

CancellationTokenSource cts = new CancellationTokenSource();

Task<int> task = new Task<int>(n => DoSomeWork((int)n, cts.Token), 100, TaskCreationOptions.None);           

task.Start();

cts.Cancel();

        private static int DoSomeWork(int n, CancellationToken token)

        {

            int sum = 1;

            Console.WriteLine(“Thread {0} started”, Thread.CurrentThread.ManagedThreadId);

            checked

            {

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

                {

                    token.ThrowIfCancellationRequested();

                    sum += sum;

                }

            }

            return sum;

        }