Why doesn't my process terminate when Task has unhandled exception?

Viewed 6183

I am building a Windows Service with .NET 4.0.

I have various unhandled exceptions thrown in Tasks, but they do not terminate my process as the MSDN documentation states (Parallel Tasks - see Unobserved Task Exceptions).

"If you don't give a faulted task the opportunity to propagate its exceptions (for example, by calling the Wait method), the runtime will escalate the task's unobserved exceptions according to the current .NET exception policy when the task is garbage-collected."

It behaves like this even when I use the most simple invokation of a task:

Task.Factory.StartNew(() => { throw new Exception(); } 

The service keeps on running fine when that is called.

According to the docs, the finalizer of the Task will rethrow the exception once the Task is GC'd but this does not appear to happen. MSDN states repeatedly that normal ".NET exception policy" results in process termination.

Why doesn't this terminate my app? The only thing I can think is there is somehow a reference to the task held somewhere (is it the lambda??)

5 Answers

.NET 4.5 made some changes as to how UnobservedExceptions are handled

While unobserved exceptions will still cause the UnobservedTaskException event to be raised (not doing so would be a breaking change), the process will not crash by default.

This behavior can be configured though, so you can revert back to .Net 4.0 behavior by enabling ThrowUnobservedTaskExceptions like so:

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

It's recommended library developers enable this when testing to ensure they don't have any UnobservedExceptions being thrown. Otherwise library consumers with this setting enabled might see their programs crashing.

Related