110,530
社区成员
发帖
与我相关
我的任务
分享
CancellationTokenSource cts = new CancellationTokenSource();
Task<int> t = new Task<int>(() => Sum(cts.Token, 1000), cts.Token);
t.Start();
Console.WriteLine("Press <Enter> to cancel the operation");
Console.Read();
cts.Cancel();
try {
t.Wait();
} catch (AggregateException ex) {
ex.Handle(p => p is OperationCanceledException);
Console.WriteLine("Sum was Canceled.");
}
Thread.Sleep(10000);
static int Sum(CancellationToken token, int n) {
int sum = 0;
for (; n > 0; n--) {
token.ThrowIfCancellationRequested();
checked {
sum += n;
}
Console.Write("{0} ", n);
Thread.Sleep(1000);
}
return sum;
}
楼主懂了么?主要利用CancellationToken在任务中如果调用它的Cancel方法会抛出AggregateException异常,主线程只要捕获这个异常并且处理他,就说明任务被取消了。