如何在TPL数据流中将多个目标块与源块链接?

时间:2014-04-25 10:51:04

标签: c# .net task-parallel-library tpl-dataflow

我希望以下内容能够从两个发布者生成输出,但它只生成第一个输出:

var broadcastBlock = new BroadcastBlock<int>(null);
var transformBlock = new TransformBlock<int, int>(i => i*10);
var publish1 = new ActionBlock<int>(i => Console.WriteLine("Publisher 1:" + i));
var publish2 = new ActionBlock<int>(i => Console.WriteLine("Publisher 2:" + i));

broadcastBlock.LinkTo(transformBlock, new DataflowLinkOptions() { PropagateCompletion = true });
transformBlock.LinkTo(publish1, new DataflowLinkOptions() { PropagateCompletion = true });
transformBlock.LinkTo(publish2, new DataflowLinkOptions() { PropagateCompletion = true });

foreach (var i in Enumerable.Range(0, 5))
{
    broadcastBlock.Post(i);
}
broadcastBlock.Complete();
Task.WhenAll(publish1.Completion, publish2.Completion).Wait();

我明显缺少一些基本的东西,任何想法?

1 个答案:

答案 0 :(得分:13)

您正在将2 ActionBlock个链接到一个TransformBlock。您应该将2 ActionBlockBrodcastBlock相关联,并将BroadcastBlockTransformBlock相关联。

你有什么:

BroadCast => Transfrom => ActionBlock
                       => ActionBlock

你需要什么:

Transfrom => BroadCast => ActionBlock
                       => ActionBlock