Search code examples
c#task-parallel-libraryunobserved-exception

How to cause AggregateException with TPL?


I'm trying to recreate the conditions that will cause this exception:

System.AggregateException: A Task's exception(s) were not observed 
either by Waiting on the Task or accessing its Exception property. 
As a result, the unobserved exception was rethrown by the finalizer thread.`

I wrote this program thinking I'd cause the exception but it does not:

using System;
using System.Threading.Tasks;
namespace SomeAsyncStuff
{
    class Program
    {
        static void Main(string[] args)
        {
            Task.Factory.StartNew(() => { throw new NullReferenceException("ex"); });
            GC.Collect();
            Console.WriteLine("completed");            
        }
    }
}

In my real application, I use TPL and I did not code my exception handling right. As a result I get that exception. Now I'm trying to recreate the same conditions in a separate program to experiment with unobserved exceptions.


Solution

  • I'm the OP. I tested the GC.WaitForPendingFinalizers() but it did not help recreating the exception. The problem was that the GC.Collect() was executed before the task started.

    This is the correct code to recreate the exception:

    using System;
    using System.Threading;
    using System.Threading.Tasks;
    namespace SomeAsyncStuff
    {
        class Program
        {
            static void Main(string[] args)
            {
                Task.Factory.StartNew(() => { throw new NullReferenceException("ex"); });
    
                // give some time to the task to complete
                Thread.Sleep(3000);
    
                GC.Collect();
                // GC.WaitForPendingFinalizers();
                Console.WriteLine("completed"); 
            }
        }
    }