使用 TPL 时未触发异常

Exception not fired when using TPL

我有以下代码不会触发 AggregateException 未触发聚合异常,我不明白为什么?通常它应该作为聚合异常用于捕获异常而运行代码使用任务

   class Program
    {
        static void Main(string[] args)
        {
            var task1 = Task.Factory.StartNew(() =>
            {
                Test();
            }).ContinueWith((previousTask) =>
            {
                Test2();
            });


            try
            {
                task1.Wait();
            }
            catch (AggregateException ae)
            {
                foreach (var e in ae.InnerExceptions)
                {
                    // Handle the custom exception.
                    if (e is CustomException)
                    {
                        Console.WriteLine(e.Message);
                    }
                    // Rethrow any other exception.
                    else
                    {
                        throw;
                    }
                }
            }
        }

        static void Test()
        {
            throw new CustomException("This exception is expected!");
        }

        static void Test2()
        {
            Console.WriteLine("Test2");
        }
    }

    public class CustomException : Exception
    {
        public CustomException(String message) : base(message)
        { }
    }
}

那是因为您正在等待完成您的延续任务(运行 Test2()),而不是等待运行 Test() 的任务完成。第一个任务因异常而失败,然后继续任务对此异常不执行任何操作(您不检查 previousTask 是否失败)并成功完成。要捕获该异常,您需要等待第一个任务或继续检查它的结果:

var task1 = Task.Factory.StartNew(() =>
{
    Test();
});
var task2 = task1.ContinueWith((previousTask) =>
{
    Test2();
});

var task1 = Task.Factory.StartNew(() =>
{
    Test();
}).ContinueWith((previousTask) =>
{
    if (previousTask.Exception != null) {
        // do something with it
        throw previousTask.Exception.GetBaseException();
    }
    Test2();
}); // note that task1 here is `ContinueWith` task, not first task

当然这与你是否真的应该这样做无关,只是为了回答这个问题。