- A+
所属分类:.NET技术
- 基础操作
CancellationTokenSource cancellationTokenSource = new CancellationTokenSource(); cancellationTokenSource.Token.Register(() => { Console.WriteLine("取消了1111"); }); cancellationTokenSource.Token.Register(() => { Console.WriteLine("取消了2222"); }); cancellationTokenSource.Cancel();
取消了2222 取消了1111
- 超时自动取消
-
new CancellationTokenSource(3000);
-
cancellationTokenSource.CancelAfter(3000);
- 关联取消
CancellationTokenSource cancellationTokenSource = new CancellationTokenSource(); CancellationTokenSource cancellationTokenSource2 = new CancellationTokenSource(); cancellationTokenSource.Token.Register(() => { Console.WriteLine("取消了1111"); }); cancellationTokenSource2.Token.Register(() => { Console.WriteLine("取消了2222"); }); var linkedTokenSource = CancellationTokenSource.CreateLinkedTokenSource(cancellationTokenSource.Token, cancellationTokenSource2.Token); linkedTokenSource.Token.Register(() => { Console.WriteLine("关联令牌被取消了"); }); //cancellationTokenSource.Cancel(); cancellationTokenSource2.Cancel();
关联令牌被取消了 取消了2222
令牌1和2的任意一个取消,关联令牌linkedTokenSource就会被取消。但是关联令牌linkedTokenSource取消,令牌1和2并不会取消。 - 判断取消
CancellationTokenSource cancellationTokenSource = new CancellationTokenSource(); cancellationTokenSource.Token.Register(() => { Console.WriteLine("取消了1111"); }); Task.Run(async () => { while (!cancellationTokenSource.IsCancellationRequested) { Console.WriteLine("一直在执行..."); await Task.Delay(1000); } }); cancellationTokenSource.CancelAfter(3000);
一直在执行... 一直在执行... 一直在执行... 取消了1111
CancellationTokenSource cancellationTokenSource = new CancellationTokenSource(); Task.Run(async () => { try { while (true) { //如果操作被取消则直接抛出异常 cancellationTokenSource.Token.ThrowIfCancellationRequested(); Console.WriteLine("一直在执行..."); await Task.Delay(1000); } } catch (OperationCanceledException ex) { Console.WriteLine("取消了!"); } }); cancellationTokenSource.CancelAfter(3000);
一直在执行... 一直在执行... 一直在执行... 取消了!
使用ThrowIfCancellationRequested会抛出OperationCanceledException异常,需要自己捕获处理