private void button1_Click(object sender, EventArgs e){//定义一个为可取消资源标志CancellationTokenSource cts = new CancellationTokenSource();//定义二个为可取消资源标志CancellationTokenSource cts1 = new CancellationTokenSource();//实现一个可取消操作的回调函数,ThreadPool.QueueUserWorkItem(o => Count(cts.Token, 1000000));//为可取消资源标志注册取消后的回调函数(无参,无返回值,匿名委托)cts.Token.Register(() => Console.WriteLine("Canceled 1")); //为可取消资源标志注册取消后的回调函数(有参,无返回值,显式申明委托)cts.Token.Register(o => TestCancellationMethead(1000, 10), true);cts1.Token.Register(() => Console.WriteLine("Canceled 2"));///连接两个可取消资源标志var LinkedCts = CancellationTokenSource.CreateLinkedTokenSource(cts.Token, cts1.Token);///给连接后的可取消资源标志集注册回调函数(匿名委托),集合中任意一个可取消资源标志取消,都将触发该回调函数LinkedCts.Token.Register(() => Console.WriteLine("linkedCts canceled"));Thread.Sleep(300);cts.Cancel();}void TestCancellationMethead(int x, int y){Console.WriteLine("取消后的回调函数" + x + y);}/// <summary>/// 一个可取消操作的回调函数,函数的关键是传入一个CancellationToken对象/// </summary>/// <param name="token"></param>/// <param name="countTo"></param>void Count(CancellationToken token, Int32 countTo){Console.WriteLine("一个可取消的操作开始执行");for (int count = 0; count < countTo; count++){if (token.IsCancellationRequested){Console.WriteLine("$" + count.ToString());Console.ReadLine();break;}Console.WriteLine("|" + count.ToString());Console.ReadLine();}}
bool IsCancellationRequested = false;private void button2_Click(object sender, EventArgs e){ThreadPool.QueueUserWorkItem(o => Count(1000000));Thread.Sleep(300);IsCancellationRequested = true;}void Count(Int32 countTo){Console.WriteLine("一个可取消的操作开始执行");for (int count = 0; count < countTo; count++){if (IsCancellationRequested){Console.WriteLine("一个可取消的操作被取消" + count.ToString());break;}Console.WriteLine(count.ToString());}}