I am experimenting with Task support in .NET 4.0 - in particular with continuation support. I am perplexed that I cannot figure out how to get continued with the TaskContinuationOptions.OnlyOnCanceled checkbox TaskContinuationOptions.OnlyOnCanceled . If I execute ThrowIfCancellationRequested in my working routine, it only seems to propagate from the continuation as an error instead of the undo operation. For example, given this 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<int>(_ => Sum(cts.Token, n), cts.Token); task.ContinueWith(t => { DumpThreadId("ContinueWith Completed, ", newline:false); Console.WriteLine("The result is " + t.Result); }, TaskContinuationOptions.OnlyOnRanToCompletion); task.ContinueWith(t => { DumpThreadId("ContinueWith Faulted, ", newline: false); Console.WriteLine(t.Exception.InnerExceptions[0].Message); }, TaskContinuationOptions.OnlyOnFaulted); task.ContinueWith(_ => { 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 > 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); } } }
It is output:
ThreadId: 9 main method Computing sum of 10000 ... Done. ThreadId: 10 from Sum method ThreadId: 10 ContinueWith Faulted, The operation was canceled.
How do I exit my working method (Sum) to continue completing OnlyOnCanceled ?
source share