如何使用CancellationToken取消任务?

所以我有这个代码:

//CancelationToken CancellationTokenSource src = new CancellationTokenSource(); CancellationToken ct = src.Token; ct.Register(() => Console.WriteLine("Abbruch des Tasks")); //Task Task t = new Task(() => { System.Threading.Thread.Sleep(1000); if (ct.IsCancellationRequested) { try { //Throw ct.ThrowIfCancellationRequested(); } catch (OperationCanceledException) { Console.WriteLine( "ThrowIfCancellationRequested() liefert eben eine Exception"); } } }, ct); //Run Task and Cancel t.Start(); src.CancelAfter(350); t.Wait(); // Get Information Console.WriteLine("Canceled: {0} . Finished: {1} . Error: {2}", t.IsCanceled, t.IsCompleted, t.IsFaulted); 

所以在这种情况下我取消了我的任务,但最后我的输出是:“取消:假。完成:真。错误:错误”

在我看来,它应该是“取消:真实。完成:错误”。 为什么我得到这个结果? 因为我试图抓住exception?

我已经尝试过没有try-catch块,但是由于OperationCanceledException,我的程序停止了。 有人能帮助我吗?

您正在吞噬exception,因此任务在您实际处理exception时被标记为已完成,并且不会向外传播。

相反,不要在委托中捕获exception,将其捕获到外部:

 void Main() { CancellationTokenSource src = new CancellationTokenSource(); CancellationToken ct = src.Token; ct.Register(() => Console.WriteLine("Abbruch des Tasks")); Task t = Task.Run(() => { System.Threading.Thread.Sleep(1000); ct.ThrowIfCancellationRequested(); }, ct); src.Cancel(); try { t.Wait(); } catch (AggregateException e) { // Don't actually use an empty catch clause, this is // for the sake of demonstration. } Console.WriteLine("Canceled: {0} . Finished: {1} . Error: {2}", t.IsCanceled, t.IsCompleted, t.IsFaulted); }