I would like to run something like this and wait on it, as a whole:
Task task1 = Task.Factory.StartNew(() => MethodThatCouldThrow());
Task task2 = task1.ContinueWith(t => HandleFailure(t.Exception),
TaskContinuationOptions.OnlyOnFaulted);
Note that there are a few discussions on the topic already (links below), but they do not quite answer this:
- How can one wait on one thing to ensure work is done(*work is defined as main task plus possible continuation)
How can one avoid exception handling for normal cases. The normal cases are:
- task1 completes (RanToCompletion), and task2 does not run (Canceled)
- task1 faults (Faulted), but task2 successfully handles it (RanToCompletion) (other cases are not normal and should throw, for example task2 faults)
Why can't I wait just on task2? Because it's "Canceled" if task1 succeeds.
Why can't I wait just on task1? Because it's "Faulted" if it failed (and task2 may still be running).
Why can't I wait on both tasks? Because task2 is "Canceled" if task1 succeeds, and this wait throws.
Couple of possible workarounds (however they do not meet desired conditions):
- unconditional continuation, which checks what to do
- conditional continuation but more complex wait, for example, wait on task2 and ignore cancelation exception if task1 succeeded.
Relevant threads I could find:
Waiting on a Task with a OnlyOnFaulted Continuation causes an AggregateException
Using Tasks with conditional continuations
Thanks!