Unobserved task exceptions in .NET4

According to some articles and blogs a code like the following one should lead to an exception in .NET 4

static void Main(string[] args)
    {
        Task.Factory.StartNew(() => { throw new Exception(); });
        Thread.Sleep(1000);
        GC.Collect();
        GC.WaitForPendingFinalizers();
        Console.WriteLine("Completed"); 
    }

Expected exception:

Unhandled 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. ---> System.InvalidOperationException: Operation is not valid due to the current state of the object.

But it doesn`t. .NET 4 applications on my PC behave like .NET 4.5:

  • they don`t throw that aggregate exception by default
  • they detect the following setting in the configuration file:

< ThrowUnobservedTaskExceptions enabled="true"/>

Looks like .NET 4 has been patched to get the same behavior that .NET 4.5 has. It it true or I have some troubles with my configuration? Or any .NET4 app (not targeting 4.5) will behave that way if 4.5 is installed? Thanks in advance.

Jon Skeet
people
quotationmark

My guess is that you're actually running on .NET 4.5. Bear in mind that .NET 4.5 is effectively installed over the top of .NET 4. Even if your application is targeted at .NET 4, if the user has installed .NET 4.5 you'll get the new behaviour.

It's entirely possible for a user to genuinely only have .NET 4 installed though...

people

See more on this question at Stackoverflow