AggregateException is not caught in Task.Wait ()

I am trying to catch a NullReferenceException that will be thrown by the Task.Factory.StartNew method. I think this should be captured by a try statement using the task.Wait () method. I also mentioned Why wasn't this exception caught? but I have no idea. Could 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();
        }
    }
}

      

+3


source to share


2 answers


This behavior has to do with the VS debugger, not your code.

If you are in debug mode and have Only My Code enabled (which is the default setting for most languages), disable it to do the trick.

To turn off Only My Code, go to Tools> Options> Debugging> General and uncheck Only My Code.



If you're wondering what the Just My Code feature does, here's an excerpt from msdn .

Include only my code
When this feature is enabled, the debugger displays and enters only the user code ("My Code"), ignoring the system code and other code that is optimized or that does not have debug symbols.

+2


source


If you want to handle an exception for a task, check to see if it has been called. If it is not faulty, continue.

   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 is return true;

invalid in this case because the method has no return type.

+1


source







All Articles