繁体   English   中英

Task.Wait()未捕获AggregateException

[英]AggregateException not caught by Task.Wait()

我正在尝试捕获将由Task.Factory.StartNew方法抛出的NullReferenceException。 我认为它应该通过task.Wait()方法的'try'语句来捕获。 我也提到为什么这个例外没有被抓住? ,但不知道。 你会分享你的智慧吗?

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的调试器而不是您的代码引起的。

如果您处于调试模式并且启用了“我的代码” (这是大多数语言的默认设置),则将其关闭应该可以解决问题。

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

如果您想知道启用Just My Code功能的功能,请参阅msdn的摘录。

启用我的代码
启用此功能后,调试器仅显示和步入用户代码(“我的代码”),忽略系统代码和其他优化的代码或没有调试符号的代码。

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

   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; 在这种情况下无效,因为方法没有返回类型。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM