C# Task使用CancellationTokenSource取消任务
-
使用CancellationTokenSource取消任务
CancellationTokenSource Source = new CancellationTokenSource(); Task T = Task.Factory.StartNew(() => { //如果Token被取消 while (!Source.IsCancellationRequested) { Thread.Sleep(100); Console.WriteLine("当前Thread正在运行{0}", Thread.CurrentThread.ManagedThreadId); } }, Source.Token); Thread.Sleep(1000); Source.Cancel();
取消的回调方法
CancellationTokenSource Source = new CancellationTokenSource(); Source.Token.Register(() => { Console.WriteLine("当前的Source已经被取消"); }); Task T = Task.Factory.StartNew(() => { while (!Source.IsCancellationRequested) { Thread.Sleep(100); Console.WriteLine("当前Thread正在运行{0}", Thread.CurrentThread.ManagedThreadId); } }, Source.Token); Thread.Sleep(1000); Source.Cancel();
延时取消
CancellationTokenSource Source = new CancellationTokenSource(); Source.Token.Register(() => { Console.WriteLine("当前的Source已经被取消"); }); Task T = Task.Factory.StartNew(() => { while (!Source.IsCancellationRequested) { Thread.Sleep(100); Console.WriteLine("当前Thread正在运行{0}", Thread.CurrentThread.ManagedThreadId); } }, Source.Token); //延时取消 Source.CancelAfter(new TimeSpan(0, 0, 0, 5));
取消的组合
//只要一个被取消,comineSource的组合就被取消,类似于WhenAny CancellationTokenSource Source = new CancellationTokenSource(); Source.Cancel(); CancellationTokenSource Source2 = new CancellationTokenSource(); //comineSource 里面只要有一个被取消了,comineSource的状态就被取消 var comineSource = CancellationTokenSource.CreateLinkedTokenSource(Source.Token, Source2.Token); Console.WriteLine("s1={0},s2={1},s3={2}", Source.IsCancellationRequested, Source2.IsCancellationRequested, comineSource.IsCancellationRequested);
-
作者:阿笨
【官方QQ一群:跟着阿笨一起玩NET(已满)】:422315558
【官方QQ二群:跟着阿笨一起玩C#(已满)】:574187616
【官方QQ三群:跟着阿笨一起玩ASP.NET(已满)】:967920586
【官方QQ四群:Asp.Net Core跨平台技术开发(可加入)】:829227829
【官方QQ五群:.NET Core跨平台开发技术(可加入)】:647639415
【网易云课堂】:https://study.163.com/provider/2544628/index.htm?share=2&shareId=2544628
【腾讯课堂】:https://abennet.ke.qq.com
【51CTO学院】:https://edu.51cto.com/sd/66c64
【微信公众号】:微信搜索:跟着阿笨一起玩NET