Note that there are some explanatory texts on larger screens.

plurals
  1. POUsing Tasks with conditional continuations
    text
    copied!<p>I'm a little confused about how to use Tasks with conditional Continuations.</p> <p>If I have a task, and then I want to continue with a tasks that handle success and error, and then wait on those to complete. </p> <pre><code>void FunctionThrows() {throw new Exception("faulted");} static void MyTest() { var taskThrows = Task.Factory.StartNew(() =&gt; FunctionThrows()); var onSuccess = taskThrows.ContinueWith( prev =&gt; Console.WriteLine("success"), TaskContinuationOptions.OnlyOnRanToCompleted); var onError = taskThrows.ContinueWith( prev =&gt; Console.WriteLine(prev.Exception), TaskContinuationOptions.OnlyOnFaulted); //so far, so good //this throws because onSuccess was cancelled before it was started Task.WaitAll(onSuccess, onError); } </code></pre> <p>Is this the preferred way of doing task success/failure branching? Also, how am I supposed to join all these tasks, suppose I've created a long line of continuations, each having their own error handling.</p> <pre><code> //for example var task1 = Task.Factory.StartNew(() =&gt; ...) var task1Error = task1.ContinueWith( //on faulted var task2 = task1.ContinueWith( //on success var task2Error = task2.ContinueWith( //on faulted var task3 = task2.ContinueWith( //on success //etc </code></pre> <p>Calling <code>WaitAll</code> on these invariably throws, because some of the continuations will be cancelled due to the <code>TaskContinuationOptions</code>, and calling <code>Wait</code> on a cancelled task throws. How do I join these without getting the "A task was cancelled" exception"?</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload