参考:http://www.cnblogs.com/scy251147/archive/2013/01/04/2843875.html
-
static void TaskWithCancellation()
-
{
-
var cancellationTokenSource = new CancellationTokenSource();
-
var cancellationToken = cancellationTokenSource.Token; //主要用于任务取消操作的信号量设置
-
-
Task t = new Task(() =>
-
{
-
int i = 0;
-
while (true)
-
{
-
i++;
-
Thread.Sleep(1000);
-
Console.WriteLine("this is task iteration " + i);
-
-
//注册信号量,如果用户取消,那么将会中断在此处
-
cancellationToken.ThrowIfCancellationRequested();
-
-
Console.WriteLine("Test to see if below can be excuted...");
-
Console.WriteLine("I am not excute");
-
}
-
}, cancellationToken);
-
-
t.Start(); //开始任务
-
-
Thread.Sleep(1000);
-
-
cancellationTokenSource.Cancel(); //取消任务
-
-
try
-
{
-
t.Wait();
-
}
-
catch (AggregateException e)
-
{
-
if (e.InnerException is OperationCanceledException)
-
Console.WriteLine("the opeartion has been canceled...");
-
else
-
Console.WriteLine("encounter some unexpected exceptions...");
-
}
-
}