c# - 使用 TPL 时不会引发异常

标签 c# .net task-parallel-library

我有以下代码,它不会引发 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

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

关于c# - 使用 TPL 时不会引发异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46955238/

相关文章:

c# - 将此 foreach 产量重写为 linq 产量?

asynchronous - 从 Azure 表结构读取 N 个实体的最有效方法是什么

c# - .Net 4.0 中没有 ConcurrentList<T> 吗?

C# winform 删除然后将更多项目添加到面板控件

c# - .Net 中的类型转发 : Does the class forwarded need to inherit from the Type class?

c# - 仅检测来自 Kinect 正前方用户的语音

c# - Visual Studio 2015 社区 - 正则表达式查找和替换

c# - Travis CI 上使用 Mono 的 NuGet 包恢复失败

c# - 为什么通过 TPL/Tasks 执行此代码时会失败?

c# - 在 WinForms ListView C# 中删除突出显示并添加选择边框