示例: .NET Framework提供的标准取消操作模式
using System;
using System.Threading;
namespace CancellationTokenSourceTest
{
class Program
{
static void Main(string[] args)
{
//协作式取消和超时
CancellationTokenSource cts = new CancellationTokenSource();
//注册取消后的回调,会按倒序执行
cts.Token.Register(() => { Console.WriteLine("token cts canceled callback1"); });
cts.Token.Register(() => { Console.WriteLine("token cts canceled callback2"); });
ThreadPool.QueueUserWorkItem(o=>Count(cts.Token, 1000));
Console.WriteLine("Press <Enter> to cancel the operation.");
Console.ReadLine();
cts.Cancel();//如果Count方法已返回,Cancel没有任何效果
Console.ReadLine();
}
private static void Count(CancellationToken token, Int32 countTo)
{
for (int count = 0; count < countTo; count++)
{
if (token.IsCancellationRequested)
{
Console.WriteLine("Count is cancelled");
break;//退出循环以停止操作
}
Console.WriteLine(count);
Thread.Sleep(200);
}
Console.WriteLine("Count is done");
}
}
}
运行测试