0
votes

I build a small sample application in .Net 4.0 to test some task exception handling. I write the code below

       Task.Factory.StartNew(() =>
       {
           throw new Exception("Exception");
       }
       Thread.Sleep(100);
       GC.Collect();
       GC.WaitForPendingFinalizers();

I expected, as my application is net 4.0, that I will get an unhandled exception but nothing happens. I see in the post UnobservedTaskException is not killing the process that even if your application is .Net 4.0 if you have Net framework 4.5 installed, it will run on this later.
Indeed when I add :

 <runtime> 
    <ThrowUnobservedTaskExceptions enabled="true"/> 
 </runtime> 

The exception is thrown as with application in 4.5

Can someone explain what is the general principle about application version and installed framework version?

1

1 Answers

2
votes

The "general principle" is that .NET version 4.5 and up will behave as much as possible like .NET 4.0 when you originally targeted 4.0 in your project. It knows what you targeted thanks to the [TargetFrameworkAttribute] that the compiler embedded in your assembly.

That's pretty important of course, this design change in .NET 4.5 is heavily breaking. You would not want a .NET 4.0 app that previously ignored the exception and kept on chugging anyway to suddenly fail when it runs on a newer runtime version. A lot more common then you might assume, especially so since there wasn't a decent way to discover these exceptions. This was a very bad design choice and Microsoft corrected it in 4.5

It just has some config settings that you can use to override this compatibility behavior, ThrowUnobservedTaskExceptions is one of them. Back-porting the behavior to a 4.0 app was considered useful, it certainly is. If you run your app on a machine that only has 4.0 then it has no effect. Another example is here.

The code that does this is located here. The internal System.CLRConfig class is new in 4.5. Actual implementation is inside the CLR since the code that parses the .config file is located there as well.