Main 程序[分别调用三个方法]
static void Main(string[] args) { using (CancellationTokenSource cts = new CancellationTokenSource()) { CancellationToken token = cts.Token; ThreadPool.QueueUserWorkItem(p => AsyncOperation(token)); Thread.Sleep(TimeSpan.FromSeconds(2)); cts.Cancel(); }; //休眠两秒,否则主线程结束了,新的线程也会结束 Thread.Sleep(TimeSpan.FromSeconds(2)); }
方法一
static void AsyncOperation(CancellationToken token) { Console.WriteLine("开始第一个任务"); for (int i = 0; i < 5; i++) { if (token.IsCancellationRequested) { Console.WriteLine(i + ":" + token.IsCancellationRequested.ToString()); return; } else { Console.WriteLine(i + ":" + token.IsCancellationRequested.ToString()); } Thread.Sleep(TimeSpan.FromSeconds(1)); } Console.WriteLine("任务执行完成"); }
运行结果
方法二
static void AsyncOperation2(CancellationToken token) { try { Console.WriteLine("开始第二个任务"); for (int i = 0; i < 5; i++) { token.ThrowIfCancellationRequested(); Thread.Sleep(TimeSpan.FromSeconds(1)); Console.WriteLine("第二个任务执行完成"); } } catch (OperationCanceledException ex) { Console.WriteLine("第二个任务被取消了"); } }
运行结果:
方法三
static void AsyncOperation3(CancellationToken token) { bool cancelflag = false; token.Register(() => cancelflag = true);//被取消时cancelflag会设置为True Console.WriteLine("开始第三个任务"); for (int i = 0; i < 5; i++) { if (cancelflag == true) { Console.WriteLine("第三个任务被取消了"); return; } else { Console.WriteLine(i + ":" + token.IsCancellationRequested.ToString()); } Thread.Sleep(TimeSpan.FromSeconds(1)); } Console.WriteLine("第三个任务执行完成"); }
运行结果: