Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Preserve exception when continuing Task<T>

I've got a Task<T>:

Task<A> someTask = ...

This task can result in being successful, faulted or cancelled.

I want to transform the result when the task is successful, and preserve the outcome if not.

This seems to be really difficult when someTask throws an exception.

What I've tried:

Task<B> resultTask = StartMyTask().ContinueWith<B>(
    t => Foo(t.Result),
    TaskContinuationOptions.OnlyOnRanToCompletion);

This results in resultTask being cancelled if someTask faults. I want it to fault.

Task<B> resultTask = StartMyTask().ContinueWith<B>(
    t => Foo(t.Result));

This breaks into the Visual Studio debugger because .Result throws an exception. If I press F5, resultTask faults as expected, but it smells.

Is there any way to let resultTask to have the same outcome as someTask if someTask faults?


Essentially what I'm trying to do is to express something like this with tasks:

int F()
{
    throw new SomeException();
}

string G(int x)
{
    return x.ToString();
}

try
{
    string result = G(F());
}
catch (SomeException e)
{
    ...
}
like image 440
dtb Avatar asked Dec 01 '10 18:12

dtb


1 Answers

I suspect the original exception will be in the AggregateException within the AggregateException if you see what I mean - you just need to unwrap twice, or call AggregateException.Flatten() on the outer AggregateException.

like image 91
Jon Skeet Avatar answered Sep 28 '22 03:09

Jon Skeet