基礎操作 CancellationTokenSource cancellationTokenSource = new CancellationTokenSource(); cancellationTokenSource.Token.Register(() => { Console.WriteLine ...
- 基礎操作
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異常,需要自己捕獲處理