Advertisement
ivandrofly

TPL_part_1_cancelling_task

Jan 19th, 2015
373
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.57 KB | None | 0 0
  1. using System;
  2. using System.Threading;
  3. using System.Threading.Tasks;
  4.  
  5. namespace TPL_part_1_cancelling_task
  6. {
  7.     class Program
  8.     {
  9.         static void Main(string[] args)
  10.         {
  11.             //creating the cancelation token
  12.             CancellationTokenSource cancellationTokenSource = new CancellationTokenSource();
  13.             CancellationToken token = cancellationTokenSource.Token;
  14.  
  15.             //creating the task
  16.             Task task = new Task(() =>
  17.             {
  18.                 for (int i = 0; i < 100000; i++)
  19.                 {
  20.                     if (token.IsCancellationRequested)
  21.                     {
  22.                         Console.WriteLine("Cancel() called.");
  23.                         return;
  24.                     }
  25.                  
  26.                     Console.WriteLine("Loop value {0}", i);
  27.                 }
  28.             }, token);
  29.  
  30.             Console.WriteLine("Press any key to start task");
  31.             Console.WriteLine("Press any key again to cancel the running task");
  32.             Console.ReadKey();
  33.            
  34.             //starting the task
  35.             task.Start();
  36.            
  37.             //reading a console key
  38.             Console.ReadKey();
  39.            
  40.             //canceling the task
  41.             Console.WriteLine("Canceling task");
  42.             cancellationTokenSource.Cancel();
  43.  
  44.             Console.WriteLine("Main method complete. Press any key to finish.");
  45.             Console.ReadKey();
  46.         }
  47.     }
  48. }
  49. // http://www.c-sharpcorner.com/UploadFile/f9f215/parallel-programming-part-1-introducing-task-programming-l/
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement