协作式取消和超时
1 internal static class CancellationDemo 2 { 3 public static void Go() 4 { 5 //向应该被取消的CancellationToken发送信号 6 CancellationTokenSource cancellationTokenSource = new CancellationTokenSource(); 7 8 ThreadPool.QueueUserWorkItem(o => Count(cancellationTokenSource.Token, 100)); 9 10 //指定毫秒(2000)后取消操作 11 //cancellationTokenSource.CancelAfter(2000); 12 13 Console.WriteLine("Press <Enter> to cancel the operation."); 14 15 Console.ReadLine(); 16 17 //如果Count方法已返回,Cancel无任何效果 18 cancellationTokenSource.Cancel(); 19 //Cancel立即返回,方法从这里继续执行 20 21 Console.ReadLine(); 22 } 23 24 private static void Count(CancellationToken cancellationToken, int countTo) 25 { 26 for (int i = 0; i < countTo; i++) 27 { 28 if (cancellationToken.IsCancellationRequested) 29 { 30 Console.WriteLine("Count is cancelled."); 31 break; 32 } 33 Console.WriteLine(i); 34 Thread.Sleep(200); 35 } 36 Console.WriteLine("Count is done."); 37 } 38 }