private void button1_Click(object sender, EventArgs e)
{
//定义一个为可取消资源标志
CancellationTokenSource cts = new CancellationTokenSource();
//定义二个为可取消资源标志
CancellationTokenSource cts1 = new CancellationTokenSource(); //实现一个可取消操作的回调函数,
ThreadPool.QueueUserWorkItem(o => Count(cts.Token, )); //为可取消资源标志注册取消后的回调函数(无参,无返回值,匿名委托)
cts.Token.Register(() => Console.WriteLine("Canceled 1")); //为可取消资源标志注册取消后的回调函数(有参,无返回值,显式申明委托)
cts.Token.Register(o => TestCancellationMethead(, ), 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();
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 = ; 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());
Thread.Sleep();
IsCancellationRequested = true;
} void Count(Int32 countTo)
{
Console.WriteLine("一个可取消的操作开始执行");
for (int count = ; count < countTo; count++)
{
if (IsCancellationRequested)
{
Console.WriteLine("一个可取消的操作被取消" + count.ToString());
break;
}
Console.WriteLine(count.ToString());
}
}