using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Threading;
namespace TaskApp
{
class Program
{
static void Main(string[] args)
{
//CancellationTokenSource:IDispose
using (CancellationTokenSource cts = new CancellationTokenSource())
{
ThreadPool.QueueUserWorkItem(o => Caculate(cts.Token, 60));
Console.ReadKey();
//lanch cancel method
cts.Cancel();
Console.ReadKey();
}
}
/// <summary>
/// Caculate
/// </summary>
/// <param name="ct">CancellationToken</param>
/// <param name="maxNumber"></param>
private static void Caculate(CancellationToken ct,int maxNumber)
{
int sum = 0;
for (int i = 0; i < maxNumber; i++)
{
if (!ct.IsCancellationRequested)
{
Thread.Sleep(1000);
sum += i;
}
else
{
Console.WriteLine("Caculate is cancelled:sum={0}", sum);
return;
}
}
Console.WriteLine("Caculate Finished:{0}!",sum);
}
}
}
CancellationToken 中肯定存在一种传入方法后能实时刷新的机制,CancellationTokenSource 的实例调用 Cancel方法后 ,Caculate 方法能感知到这种变化。