简体   繁体   English

Task.Wait()未捕获AggregateException

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

I'm trying to catch an NullReferenceException which is going to be thrown by Task.Factory.StartNew method. 我正在尝试捕获将由Task.Factory.StartNew方法抛出的NullReferenceException。 I think it should be caught by 'try' statement with task.Wait() method. 我认为它应该通过task.Wait()方法的'try'语句来捕获。 I also referred to Why is this exception not caught? 我也提到为什么这个例外没有被抓住? , but have no idea. ,但不知道。 Would you share your wisdom? 你会分享你的智慧吗?

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

This behavior is due to VS's debugger and not your code. 这种行为是由VS的调试器而不是您的代码引起的。

If you're in debug mode and have Just My Code enabled (which is the default setting for most languages), turning it off should do the trick. 如果您处于调试模式并且启用了“我的代码” (这是大多数语言的默认设置),则将其关闭应该可以解决问题。

To disable the Just My Code feature, go to Tools > Options > Debugging > General and uncheck Just My Code checkbox. 要禁用“我的代码”功能,请转到“工具”>“选项”>“调试”>“常规”,然后取消选中“仅我的代码”复选框。

If you're wondering what enabling Just My Code feature does, here's a excerpt from msdn . 如果您想知道启用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. 启用此功能后,调试器仅显示和步入用户代码(“我的代码”),忽略系统代码和其他优化的代码或没有调试符号的代码。

If you want to handle exception for a task , check if it is faulted. 如果要处理任务的异常,请检查它是否存在故障。 If it is not faulted continue with execution. 如果没有故障继续执行。

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

And the return true; 而且return true; is invalid in this case as method does not have a return type. 在这种情况下无效,因为方法没有返回类型。

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

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