关于 CancelToken 的学习笔记

最简单的例子:

 1     private static async Task Main(string[] args)
 2         {
 3             CancellationTokenSource tokenSource = new CancellationTokenSource();
 4             CancellationToken cancellationToken = tokenSource.Token;
 5             //打印被取消
 6             cancellationToken.Register(() => System.Console.WriteLine("被取消了."));
 7             //模拟传递的场景
 8             _ = Task.Run(async () => {
 9                 //while (!cancellationToken.IsCancellationRequested)
10                 //{
11                     System.Console.WriteLine("一直在执行...");
12                     await Task.Delay(1000, cancellationToken);
13                 //}
14             });
15             //5s之后取消
16             //tokenSource.CancelAfter(5000);
17             tokenSource.Cancel();
18             Console.ReadKey();
19         }

 

posted @ 2023-03-25 21:20  博二爷  阅读(36)  评论(0编辑  收藏  举报