Note that there are some explanatory texts on larger screens.

plurals
  1. POWhich Task in a continuation chain was running when cancelled?
    primarykey
    data
    text
    <p>I have a continuation chain of <code>Task</code>s that may be cancelled, say, after a timeout occurs. I want to identify which task was running when the cancellation happened. Here's what I'm talking about:</p> <pre><code>CancellationTokenSource cts = new CancellationTokenSource(); Task timeoutTask = Task.Delay(5000).ContinueWith((t) =&gt; cts.Cancel()); Task workChain = Task.Factory.StartNew((t) =&gt; { Console.WriteLine("Running task " + Task.CurrentId); Thread.Sleep(1000); }, -1, cts.Token); Task parent = workChain; for (int i = 0; i &lt; 10; i++) { parent = parent.ContinueWith((t, o) =&gt; { Console.WriteLine("Running task " + Task.CurrentId); Console.WriteLine("Last Task.AsyncState = " + t.AsyncState); Thread.Sleep(1000); }, i, cts.Token, TaskContinuationOptions.OnlyOnRanToCompletion, TaskScheduler.Current); } parent.ContinueWith((t) =&gt; { Console.WriteLine("Cancel task " + Task.CurrentId); Console.WriteLine("Last running Task.AsyncState = " + t.AsyncState); }, TaskContinuationOptions.OnlyOnCanceled); </code></pre> <p>When I run the above, the antecedent passed into the <code>OnlyOnCanceled</code> one isn't the task that was running when things were cancelled. I know why: the <code>OnlyOnCanceled</code> task <em>is</em> parented by the last task created in the loop, and when the timeout occurs, all tasks that aren't completed are marked as canceled without being started.</p> <p>Having each task check the state of the token and store something elsewhere works most of the time, but there's a small chance that the cancellation happens after one task completes before the next task begins. In that case, I don't find out anything about the first canceled task. I could always store something when a task starts and something else if it is canceled, but this starts to feel kludgy pretty quickly.</p>
    singulars
    1. This table or related slice is empty.
    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.
 

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