在OnlyOnFaulted Continuation中等待任务会导致AggregateException

我有一些简单的代码作为repro:

var taskTest = Task.Factory.StartNew(() => { System.Threading.Thread.Sleep(5000); }).ContinueWith((Task t) => { Console.WriteLine("ERR"); }, TaskContinuationOptions.OnlyOnFaulted); try { Task.WaitAll(taskTest); } catch (AggregateException ex) { foreach (var e in ex.InnerExceptions) Console.WriteLine(e.Message + Environment.NewLine + e.StackTrace); } 

但是,我得到一个意外的TaskCanceledException被抛出在try catch块(它在AggregateException InnerExceptions对象)。 “任务被取消了”。

为什么我得到这个exception? 任务的延续永远不会触发,没有任何exception产生,但我仍然在等待时得到聚合exception….

我希望有人可以解释这对我有意义:)

你并没有等待一个OnlyOnFaulted延续的任务 – 你正在等待这个延续(由ContinueWith返回)。 继续不会因为原来的任务正常返回而被触发,所以它的行为就好像被取消了一样。

我感觉合理。

我怀疑你想创build任务,添加延续,但是等待原来的任务:

 var taskTest = Task.Factory.StartNew(() => { System.Threading.Thread.Sleep(5000); }); taskTest.ContinueWith((Task t) => { Console.WriteLine("ERR"); }, TaskContinuationOptions.OnlyOnFaulted);