gpt4 book ai didi

task-parallel-library - 任务并行库 - 您如何通过 TaskContinuationOptions.OnlyOnCanceled 获得继续触发?

转载 作者:行者123 更新时间:2023-11-30 23:58:22 24 4
gpt4 key购买 nike

我正在试验 .NET 4.0 中的任务支持 - 特别是延续支持。我感到困惑的是,我不知道如何继续使用 TaskContinuationOptions.OnlyOnCanceled标志设置为执行。如果我做 ThrowIfCancellationRequested在我的工作程序中,它似乎只是作为错误而不是取消操作从延续中传播出来。例如,给定以下代码:

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.

我如何退出我的 worker (Sum) 方法,使得 OnlyOnCanceled延续被解雇?

最佳答案

当您使用 _ => lambda 表达式时,您使用的是

Func<Object, TResult> function, Object state

重载。如果您将 Factory.StartNew 更改为
Task.Factory.StartNew<int>(() => Sum(cts.Token, n), cts.Token);

它将调用“ContinueWith Cancelled”。

关于task-parallel-library - 任务并行库 - 您如何通过 TaskContinuationOptions.OnlyOnCanceled 获得继续触发?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3956055/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com