I have this simple TPL code:
var t = Task.Factory.StartNew(() => { throw null; })
.ContinueWith((ant) => { Console.WriteLine("Success"); },
TaskContinuationOptions.OnlyOnRanToCompletion)
.ContinueWith((ant) => { Console.WriteLine("Error"); },
TaskContinuationOptions.OnlyOnFaulted);
t.Wait();
I get an unhandled exception:
Unhandled Exception: System.AggregateException: One or more errors occurred.
...
If i put t.Wait() in a try-catch, the exception is caught there and i know it defies the whole point of using the exception continuation. Now, if i remove the completion continuation, the exception thrown by the task is handled in the exception continuation and i don’t get the above exception. Can someone throw some light on whats happening?
I am using VS2010 SP1 with .NET 4.0
ContinueWith()doesn’t return the originalTask, it returns aTaskrepresenting the continuation. And in your case that continuation is canceled, because the originalTaskdidn’t run to completion. And because the secondTaskwasn’t faulted, your thirdTaskwas canceled too, which is why you’re gettingTaskCanceledExceptionwrapped insideAggregateException.What you can do instead is to have one continuation, which does both actions. Something like:
If you do something like this often, you could create an extension method for this (plus probably a generic version for
Task<T>withAction<T>asonSuccess):Usage:
Also, this assumes you know your original
Taskwon’t be canceled. If that’s not the case, that’s one more case you need to handle.