zoukankan      html  css  js  c++  java
  • 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. }
  • 相关阅读:
    通知advice
    通知advice
    springmvc+mybatis需要的jar包与详解
    sass参考手册
    Mapper
    排序
    常见设计模式
    JavaScript之事件循环,宏任务与微任务
    字符串翻转
    eeeeeeeeeeeeeeeeeeeeee
  • 原文地址:https://www.cnblogs.com/pengzhen/p/4522998.html
Copyright © 2011-2022 走看看