Task加入取消功能

 

参考:http://www.cnblogs.com/scy251147/archive/2013/01/04/2843875.html

  1. static void TaskWithCancellation()
  2. {
  3.     var cancellationTokenSource = new CancellationTokenSource();
  4.     var cancellationToken = cancellationTokenSource.Token; //主要用于任务取消操作的信号量设置
  5.  
  6.     Task t = new Task(() =>
  7.     {
  8.         int i = 0;
  9.         while (true)
  10.         {
  11.             i++;
  12.             Thread.Sleep(1000);
  13.             Console.WriteLine("this is task iteration " + i);
  14.  
  15.             //注册信号量,如果用户取消,那么将会中断在此处
  16.             cancellationToken.ThrowIfCancellationRequested(); 
  17.  
  18.             Console.WriteLine("Test to see if below can be excuted...");
  19.             Console.WriteLine("I am not excute");
  20.         }
  21.     }, cancellationToken);
  22.  
  23.     t.Start();  //开始任务
  24.  
  25.     Thread.Sleep(1000);
  26.  
  27.     cancellationTokenSource.Cancel(); //取消任务
  28.  
  29.     try
  30.     {
  31.         t.Wait();
  32.     }
  33.     catch (AggregateException e)
  34.     {
  35.         if (e.InnerException is OperationCanceledException)
  36.             Console.WriteLine("the opeartion has been canceled...");
  37.         else
  38.             Console.WriteLine("encounter some unexpected exceptions...");
  39.     }
  40. }
posted @ 2015-05-22 18:03  _DN  阅读(256)  评论(0编辑  收藏  举报