Task.Wait() 未捕获 AggregateException

AggregateException not caught by Task.Wait()

我正在尝试捕获将由 Task.Factory.StartNew 方法抛出的 NullReferenceException。我认为它应该被 'try' 语句和 task.Wait() 方法捕获。 我也提到了 ,但不知道。你能分享你的智慧吗?

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Threading;
using System.Threading.Tasks;

namespace Csharp_study
{
    class Program
    {
        static void Main(string[] args)
        {
            Task my_task = Task.Factory.StartNew(() => { throw null; });
            try
            {
                my_task.Wait();
            }

            catch (AggregateException exc)
            {
                exc.Handle((x) =>
                    {
                        Console.WriteLine(exc.InnerException.Message);
                        return true;
                    });
            }

            Console.ReadLine();
        }
    }
}

如果要处理任务的异常,请检查它是否出错。如果没有出错继续执行。

   static void Main(string[] args)
        {
            Task my_task = Task.Factory.StartNew(() => { throw null; });

            my_task.ContinueWith(x =>
            {

                if (my_task.IsFaulted)
                {
                    Console.WriteLine(my_task.Exception.Message);

                }
                else {
                    //Continue with Execution
                }
            });
        }

并且 return true; 在这种情况下无效,因为方法没有 return 类型。

此行为是由于 VS 的调试器而不是您的代码造成的。

如果您处于调试模式并且启用了 Just My Code(这是大多数语言的默认设置),关闭它应该可以解决问题。

要禁用“仅我的代码”功能,请转至“工具”>“选项”>“调试”>“常规”并取消选中“仅我的代码”复选框。

如果您想知道启用“仅我的代码”功能有何作用,请参阅以下摘录 msdn

Enable Just My Code
When this feature is enabled, the debugger displays and steps into user code ("My Code") only, ignoring system code and other code that is optimized or that does not have debugging symbols.