C# 中通过CancellationTokenSource实现对超时任务的取消

在Task中用CancellationTokenSource来取消任务,可以手动 cancelTokenSource.Cancel()取消,还有new时就设置取消时间var cancelTokenSource = new CancellationTokenSource(2000); 也可以在任务中 cancelTokenSource.CancelAfter(2000)实现同样的效果。

            var cancelTokenSource = new CancellationTokenSource();
            //var cancelTokenSource = new CancellationTokenSource(2000);

            Task.Run(() =>
            {
                //cancelTokenSource.CancelAfter(2000);
                while (!cancelTokenSource.IsCancellationRequested)
                {
                    Console.WriteLine(DateTime.Now);
                    Thread.Sleep(1000);
                }
            }, cancelTokenSource.Token);

            Console.WriteLine("Press any key to cancel");
            Console.ReadLine();
            cancelTokenSource.Cancel();
            Console.WriteLine("Done");

 

C# 中通过CancellationTokenSource实现对超时任务的取消

上一篇:windows环境下maven的安装与环境变量配置


下一篇:CSS中的绝对定位与相对定位