Search code examples
c#taskcontinuewith

when the exception property in the Task can have a value?


I want to know when "continueWhith" has exceptions.

I made a code like this.

Task.Factory.StartNew(() =>
{
   if(HasException())
       throw new Exception("Exception");
   // Logic
}).ContinueWith(x =>
{
   // Do something to UI.
}, CancellationToken.None, TaskContinuationOptions.NotOnFaulted, 
_uiScheduler).continueWith(x =>
{
   if (x.Exception.IsNotNull()) // Exception handling here.
     ShowExceptionMessage(x.Exception);            
}

I expected to there was an exception in the task at last continueWith, but it wasn't.

Is it right that there isn't an Exception in the Task at last continueWith?

and I want to know how to set an exception property in continueWith.

Thank you.


Solution

  • Is it right that there isn't an Exception in the Task at last continueWith?

    Yes, because it's a continuation from your "Do something to UI" task. There would only be an exception in x.Exception if that second task had failed.

    In fact, I wouldn't expect you to reach either continuation, as your first task is always faulted and the first continuation explicitly says to only execute if it's not faulted.

    Alternatives:

    • Propagate the exception (if any) via the result of the second task
    • Add both continuations to the original task, instead of chaining them. (This may be what you were originally intending, in order to keep the faulted and unfaulted paths separate. In that case, attach both continuations to the first task, and use TaskContinuationOptions.OnlyOnFaulted for the second continuation - then you don't need the exception check at all.)
    • Keep a local variable with the original task so you can get at that from the second continuation

    Ideally, I'd suggest using async/await instead of all of the continuation passing though. It tends to make things a lot simpler.