0

What I am trying to do here is that based on the parent task execution I am trying to execute or cancel the subsequent async task. I am finding it hard to wrap my head around the execution of the following and trying to implement this in the most optimal way. I am looking for a way to write this in the most optimized way.

Also, I am confused as to why even after throwing up an exception it continues with the next iteration and await the task to figure out the exception thrown. I Can't find an explanation around this.

 public static async Task<TOut> AndThen<TIn, TOut>(this Task<TIn> sourceTask, Func<TIn, Task<TOut>> sf, CancellationToken cancelToken) { return await sourceTask.ContinueWith(async st => { var res = await st; // Raising cancel request in here. cancelToken.ThrowIfCancellationRequested(); return await sf(res); }, TaskContinuationOptions.NotOnFaulted & TaskContinuationOptions.NotOnCanceled).Unwrap(); } 
2
  • 3
    Try TaskContinuationOptions.NotOnFaulted | TaskContinuationOptions.NotOnCanceled rather than &. Commented Dec 24, 2019 at 13:09
  • 1
    What is the desirable outcome in case the sourceTask completes in faulted state? Commented Dec 24, 2019 at 15:14

1 Answer 1

5

As a general rule, don't use ContinueWith. Use await instead:

public static async Task<TOut> AndThen<TIn, TOut>(this Task<TIn> sourceTask, Func<TIn, Task<TOut>> sf, CancellationToken cancelToken) { var res = await st; cancelToken.ThrowIfCancellationRequested(); return await sf(res); } 
Sign up to request clarification or add additional context in comments.

2 Comments

So, to handle the faulted state of the source task - wrap it with try catch ?
If you just want to propagate the exception, then do nothing; this code already does that. If you want to do something else, then yes, use try/catch.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.