【问题标题】:Exception not fired when using TPL使用 TPL 时未触发异常
【发布时间】:2017-10-26 21:22:58
【问题描述】:

我有以下代码不会触发 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)
        { }
    }
}

【问题讨论】:

  • 确定不是调试器在您的代码有机会之前捕获它?
  • 即使我不使用调试器也会出现同样的问题。我没有收到This exception is expected
  • 我认为是因为您使用了 StartNew,因为在代码尝试等待之前发生了错误
  • 这就是为什么您应该真正使用await 而不是使用ContinueWith 手动添加延续。 await 的最大优势之一是它以大多数人期望的方式传播异常,这与 ContinueWith 不同。

标签: c# .net task-parallel-library


【解决方案1】:

这是因为您正在等待继续任务(运行 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

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

【讨论】:

  • 如果发生异常应该触发AggregateException?
  • @codejunkie 是的,如果你在回答中运行代码,你会发现AggregateException 是两种情况。
猜你喜欢
  • 2016-04-25
  • 1970-01-01
  • 2019-07-10
  • 1970-01-01
  • 1970-01-01
  • 2015-09-30
  • 1970-01-01
  • 1970-01-01
  • 2019-11-29
相关资源
最近更新 更多