c# - AggregateException 未被 Task.Wait() 捕获

标签 c# task wait aggregateexception

我正在 try catch 将由 Task.Factory.StartNew 方法抛出的 NullReferenceException。我认为它应该被带有 task.Wait() 方法的“try”语句捕获。 我还提到了 Why is this exception not caught? ,但不知道。您愿意分享您的智慧吗?

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();
        }
    }
}

最佳答案

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

如果您处于 Debug模式并且启用了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.

关于c# - AggregateException 未被 Task.Wait() 捕获,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43531278/

相关文章:

ios - 当其中一个是动画时,等待 iOS 中的两个完成的任务?

go - Goroutines节气门示例

java - 新窗口无法加载

c# - CefSharp 文档完成

c# - 在 C# 或 VBA 中以编程方式将 Jpeg 图像插入到 Visio 绘图中

c# - 我应该将 .pdf 文档保存到数据库还是需要搜索的文件夹中

c# - 什么是 C# 中 C++ vector 的良好替代品?

c# - OnlyOnRanToCompletion 和 NotOnFaulted 之间的区别?

c# - 通用任务方法实现

ssh - 在 while 循环中使用 SSH