TPL Dataflow, guarantee completion only when ALL source data blocks completed

前端 未结 5 1093
谎友^
谎友^ 2020-12-08 19:54

How can I re-write the code that the code completes when BOTH transformblocks completed? I thought completion means that it is marked complete AND the \" out queue\" is empt

5条回答
  •  一整个雨季
    2020-12-08 20:35

    Here is a method that is functionally equivalent to pkt's CompleteWhenAll method, but with slightly less code:

    public static void PropagateCompletionOfAll(IDataflowBlock[] sources,
        IDataflowBlock target)
    {
        _ = Task.WhenAll(sources.Select(b => b.Completion)).ContinueWith(t =>
        {
            if (t.IsFaulted)
            {
                target.Fault(t.Exception);
            }
            else
            {
                target.Complete();
            }
        }, TaskScheduler.Default);
    }
    

    Usage example:

    PropagateCompletionOfAll(new[] { transformBlock1, transformBlock2 }, processorBlock);
    

    You could make the case about adding the condition: else if (t.IsCanceled) { target.Fault(new OperationCanceledException()); }, but this would be inconsistent with how the built-in completion propagation works.

提交回复
热议问题