Question

I have a task with a continuation to handle errors:

var uiScheduler = TaskScheduler.FromCurrentSynchronizationContext();
var loadTask = Task<List<OrderItemViewModel>>.Factory.StartNew(() =>
{
       throw new Exception("derp");
});

var errorContinue = loadTask.ContinueWith(t =>
    {
        MainViewModel.RemoveViewModel(this);
    }, CancellationToken.None, TaskContinuationOptions.OnlyOnFaulted, uiScheduler);

The continuation is hit, but a few seconds later I receive this error in the application:

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.

Is this related to the uiScheduler? The solution to the similar question is basically what I'm doing 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

Was it helpful?

Solution

You need to actually handle (or at least observe) the exception:

var errorContinue = loadTask.ContinueWith(t =>
{
    // Observe/acknowledge the exception.  
    // You can use t.Wait(), which throws, or just grab the exception
    var exception = t.Exception; 
    MainViewModel.RemoveViewModel(this);
}, CancellationToken.None, TaskContinuationOptions.OnlyOnFaulted, uiScheduler);

This is because of this line of the documentation on exception handling in the TPL:

If you do not wait on a task that propagates an exception, or access its Exception property, the exception is escalated according to the .NET exception policy when the task is garbage-collected.

In your case, you have a continuation, but you never actually "wait on the exception" or access it's exception property. The reason my answer (in the related question you posted) works is that I'm actually using the Exception property on the Task passed through the continuation.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top