Note that there are some explanatory texts on larger screens.

plurals
  1. POWhy is a task continuation for a child task not triggered when parent is cancelled?
    primarykey
    data
    text
    <p>Consider the following C# code:</p> <pre><code>CancellationTokenSource tCancelSource = new CancellationTokenSource(); var tTask = Task.Factory.StartNew ( () =&gt; { // Start child Task.Factory.StartNew (() =&gt; { Thread.Sleep(2000); Console.WriteLine("A"); tCancelSource.Token.ThrowIfCancellationRequested(); } , tCancelSource.Token , TaskCreationOptions.AttachedToParent , TaskScheduler.Current ) .ContinueWith ( t =&gt; { Console.WriteLine("B"); } , tCancelSource.Token, TaskContinuationOptions.AttachedToParent , TaskScheduler.Current ); } , tCancelSource.Token, TaskCreationOptions.PreferFairness , TaskScheduler.Current ) .ContinueWith (t =&gt; Console.WriteLine("C")); Thread.Sleep(500); tCancelSource.Cancel(); tTask.Wait(); Console.WriteLine("Done"); Console.Read(); </code></pre> <p>The continuation of the child task does not fire, i.e. B is not printed to the Console. Commenting out the call to Cancel would print B.</p> <p>Observed:</p> <pre><code>A C </code></pre> <p>Expected</p> <pre><code>A B C </code></pre> <p>It seems that the continuation of a child task is not fired if the parent is cancelled, but I can't find this documented. Anyone have any idea why/what's going on here, or where this would be documented?</p> <p>Edit:</p> <p>I forgot to pass the cancellation token to the final continuation. Indeed, I found the documentation reads "[...]If the antecedent was canceled, the continuation will not be started", however I got confused by the option TaskContinuation.OnlyOnCanceled. Such a scenario is possible, for example </p> <pre><code>CancellationTokenSource tSource = new CancellationTokenSource(); Task tTest = Task.Factory.StartNew ( () =&gt; { throw new Exception("foobar"); }, tSource.Token).ContinueWith(t =&gt; { Console.WriteLine("A " + t.Status); } , tSource.Token , TaskContinuationOptions.NotOnFaulted , TaskScheduler.Current ) .ContinueWith ( t =&gt; { Console.WriteLine("B " + t.Status); } , tSource.Token ); tTest.Wait(); Console.Read(); </code></pre> <p>the first continuation is set to state cancelled (as its TaskContinuationOptions value causes it not to run), without the token being set to cancelled. So the last continuation does run here.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

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