Cancel a Task for Parallel Programing C#

Problem
You need to cancel a Task while it is running.
Solution
Create an instance of System.Threading.CancellationTokenSource and call the Token  roperty to obtain a System.Threading.CancellationToken. Pass a function delegate that calls the Cancel method of your Task to the Register method of CancellationToken. Cancel your Task by calling the Cancel method of CancellationTokenSource.

   1: using System;

   2: using System.Threading;

   3: using System.Threading.Tasks;

   4: namespace Sample

   5: {

   6:     class Sample

   7:     {

   8:         static void Main(string[] args)

   9:         {

  10:             // Create the token source.

  11:             CancellationTokenSource tokenSource = new CancellationTokenSource();

  12:  

  13:             // create the cancellation token

  14:             CancellationToken token = tokenSource.Token;

  15:             

  16:             // Create the task.

  17:             Task task = Task.Factory.StartNew(() => printNumbers(token), token);

  18:             

  19:             // register the task with the token

  20:             token.Register(() => notifyTaskCanceled());

  21:             

  22:             // Wait for the user to request cancellation.

  23:             Console.WriteLine("Press enter to cancel token");

  24:             Console.ReadLine();

  25:             

  26:             // Canceling.

  27:             tokenSource.Cancel();

  28:         }

  29:         static void notifyTaskCanceled()

  30:         {

  31:             Console.WriteLine("Task cancellation requested");

  32:         }

  33:         static void printNumbers(CancellationToken token)

  34:         {

  35:             int i = 0;

  36:             while (!token.IsCancellationRequested)

  37:             {

  38:                 Console.WriteLine("Number {0}", i++);

  39:                 Thread.Sleep(500);

  40:             }

  41:             throw new OperationCanceledException(token);

  42:         }

  43:     }

  44: }