Note that there are some explanatory texts on larger screens.

plurals
  1. POTask Parallel Library - How do you get a Continuation with TaskContinuationOptions.OnlyOnCanceled to Fire?
    primarykey
    data
    text
    <p>I'm experimenting with the Task support in .NET 4.0 - specifically with the continuation support. What I'm perplexed about is that I can't figure out how to get a continuation with the <code>TaskContinuationOptions.OnlyOnCanceled</code> flag set to execute. If I do a <code>ThrowIfCancellationRequested</code> in my worker routine, it only seems to propagate out of the continuation as a fault instead of a cancel operation. For instance, given this code:</p> <pre><code>using System; using System.Threading; using System.Threading.Tasks; namespace TaskExp1 { class Program { static void Main() { var n = 10000; DumpThreadId("main method"); var cts = new CancellationTokenSource(); var task = Task.Factory.StartNew&lt;int&gt;(_ =&gt; Sum(cts.Token, n), cts.Token); task.ContinueWith(t =&gt; { DumpThreadId("ContinueWith Completed, ", newline:false); Console.WriteLine("The result is " + t.Result); }, TaskContinuationOptions.OnlyOnRanToCompletion); task.ContinueWith(t =&gt; { DumpThreadId("ContinueWith Faulted, ", newline: false); Console.WriteLine(t.Exception.InnerExceptions[0].Message); }, TaskContinuationOptions.OnlyOnFaulted); task.ContinueWith(_ =&gt; { DumpThreadId("ContinueWith Cancelled, "); }, TaskContinuationOptions.OnlyOnCanceled); Console.WriteLine("Computing sum of " + n + " ..."); Thread.SpinWait(100000); cts.Cancel(); Console.WriteLine("Done."); Console.ReadLine(); } static int Sum(CancellationToken cancelToken, int n) { DumpThreadId("from Sum method"); int sum = 0; for (; n &gt; 0; n--) { Thread.SpinWait(500000); if (n == 10000) cancelToken.ThrowIfCancellationRequested(); checked { sum += n; } } return sum; } static void DumpThreadId(string msg = "", bool newline = true) { var formattedMsg = String.Format("ThreadId: {0} {1}", Thread.CurrentThread.ManagedThreadId, msg); if (newline) formattedMsg += "\n"; Console.Write(formattedMsg); } } } </code></pre> <p>This outputs:</p> <pre><code>ThreadId: 9 main method Computing sum of 10000 ... Done. ThreadId: 10 from Sum method ThreadId: 10 ContinueWith Faulted, The operation was canceled. </code></pre> <p>How do I exit my worker (Sum) method such that the <code>OnlyOnCanceled</code> continuation gets fired?</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.
    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