在A和B运行完成后没有故障或使用单个TPL方法取消后,是否可以继续执行任务C?

Kit*_*Kit 7 continuations .net-4.0 task task-parallel-library

我已经尝试过几次使用Task.Factory.ContinueWhenAll(),目的只是在所有前提条件运行完成而没有任何错误或取消时才调用一个延续.这样做会导致抛出ArgumentOutOfRangeException并显示消息,

从多个任务中排除延续的特定延续种类是无效的.参数名称:continuationOptions

例如,代码

var first = Task.Factory.StartNew<MyResult>(
    DoSomething,
    firstInfo,
    tokenSource.Token);
var second = Task.Factory.StartNew<MyResult>(
    DoSomethingElse,
    mystate,
    tokenSource.Token);
var third = Task.Factory.ContinueWhenAll(
    new[] { first, second },
    DoSomethingNowThatFirstAndSecondAreDone,
    tokenSource.Token,
    TaskContinuationOptions.OnlyOnRanToCompletion, // not allowed!
    TaskScheduler.FromCurrentSynchronizationContext());
Run Code Online (Sandbox Code Playgroud)

TPL不接受.有没有办法使用其他TPL方法做这样的事情?

Kit*_*Kit 4

似乎没有直接的方法可以做到这一点。我通过将OnlyOnRanToCompletion更改为None并检查传递到延续的每个任务的Exception是否为非空来解决这个问题。就像是

private void DoSomethingNowThatFirstAndSecondAreDone(Task<MyResult>[] requestTasks)
{
    if (requestTasks.Any(t => t.Exception != null))
        return;

    // otherwise proceed...
}
Run Code Online (Sandbox Code Playgroud)

有效,但这似乎不是一种非常令人满意的方法来处理具有多个先行条件的情况,并且打破了单例Task.Factory.ContinueWith使用的模式。