任务并行库 - 您如何通过 TaskContinuationOptions.OnlyOnCanceled 获得继续触发? [英] Task Parallel Library - How do you get a Continuation with TaskContinuationOptions.OnlyOnCanceled to Fire?
问题描述
我正在试验 .NET 4.0 中的任务支持 - 特别是延续支持.我感到困惑的是,我无法弄清楚如何在 TaskContinuationOptions.OnlyOnCanceled
标志设置为执行的情况下获得延续.如果我在我的工作例程中执行 ThrowIfCancellationRequested
,它似乎只会作为错误而不是取消操作传播到延续之外.例如,给定以下代码:
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 TaskContinuationOptions.OnlyOnCanceled
flag set to execute. If I do a ThrowIfCancellationRequested
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:
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);
}
}
}
输出:
ThreadId: 9 main method
Computing sum of 10000 ...
Done.
ThreadId: 10 from Sum method
ThreadId: 10 ContinueWith Faulted, The operation was canceled.
如何退出我的工作程序 (Sum) 方法,以便 OnlyOnCanceled
继续被触发?
How do I exit my worker (Sum) method such that the OnlyOnCanceled
continuation gets fired?
推荐答案
当您使用 _ => lambda 表达式时,您正在使用
When you are using the _ => lambda expression you are using the
Func<Object, TResult> function, Object state
过载.如果您将 Factory.StartNew 更改为
overload. If you change the Factory.StartNew to
Task.Factory.StartNew<int>(() => Sum(cts.Token, n), cts.Token);
它将调用ContinueWith Cancelled".
it will call the "ContinueWith Cancelled".
这篇关于任务并行库 - 您如何通过 TaskContinuationOptions.OnlyOnCanceled 获得继续触发?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!