我使用 TPL Dataflow 构建了两个管道:

TransformBlock => TransformBlock => BatchBlock => ....

TransformBlock => BatchBlock => TransformBlock => ....

我想完成
            / => Transform Block => TransformBlock => BatchBlock => ....
BatchBlock /
           \
            \ => Transform Block => BatchBlock => TransformBlock => ....

然而,只有第一个管道被执行。

我的代码
batchMediaBlock.LinkTo(pipelineA.FirstBlock, new DataflowLinkOptions {PropagateCompletion = true});
batchMediaBlock.LinkTo(pipelineB.FirstBlock, new DataflowLinkOptions {PropagateCompletion = true});

我怎样才能做到这一点?

最佳答案

BroadcastBlock 之后你需要一个 BatchBlock 。但请注意,完成只会传播到您的 TransformBlock 之一。请参阅下面的部分示例来处理完成:

using System.Threading.Tasks.Dataflow;

namespace MyDataflow {
    class MyDataflow {

        public void HandlingCompletion() {
            var batchBlock = new BatchBlock<int>(10);
            var broadcastBlock = new BroadcastBlock<int[]>(_ => _);
            var xForm1 = new TransformBlock<int[], int[]>(_ => _);
            var xForm2 = new TransformBlock<int[], int[]>(_ => _);

            batchBlock.LinkTo(broadcastBlock, new DataflowLinkOptions() { PropagateCompletion = true });
            broadcastBlock.LinkTo(xForm1);
            broadcastBlock.LinkTo(xForm1);

            broadcastBlock.Completion.ContinueWith(broadcastBlockCompletionTask => {
                if (!broadcastBlockCompletionTask.IsFaulted) {
                    xForm1.Complete();
                    xForm2.Complete();
                }else {
                    ((IDataflowBlock)xForm1).Fault(broadcastBlockCompletionTask.Exception);
                    ((IDataflowBlock)xForm2).Fault(broadcastBlockCompletionTask.Exception);
                }

            });

            xForm1.Completion.ContinueWith(async _ => {
                try {
                    await xForm2.Completion;
                    //continue passing completion / fault on to rest of pipeline
                } catch  {

                }
            });

        }
    }
}

或者,如果您的管道不再收敛,您可以在继续 BroacastBlock 后分别处理每个管道的完成。提供的示例将同时完成管道中的每个步骤,同步完成。

关于c# - 将多个 TransformBlock 链接到单个 BatchBlock TPL,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/42984500/

10-13 06:05