本文介绍了C#TPL数据流-完成不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
此代码永远不会到达最后一行,因为完成不会从saveBlock传播到sendBlock.我在做什么错了?
This code never reaches the last line because the completion doesn't propagate from the saveBlock to the sendBlock. What am I doing wrong?
var readGenerateBlock = new TransformBlock<int, int>(n =>
{
Console.WriteLine("Read " + n);
Thread.Sleep(15);
return n;
});
var groupingBlock = new BatchBlock<int>(10);
var saveBlock = new TransformManyBlock<int[], int>(n =>
{
Console.WriteLine("Saving {0} items [{1}; {2}]", n.Count(), n.First(), n.Last());
Thread.Sleep(150);
return n;
});
var sendBlock = new TransformBlock<int, int>(n =>
{
Console.WriteLine("Sending {0}", n);
Thread.Sleep(25);
return n;
}, new ExecutionDataflowBlockOptions { MaxDegreeOfParallelism = 2 });
readGenerateBlock.LinkTo(groupingBlock, new DataflowLinkOptions { PropagateCompletion = true });
groupingBlock.LinkTo(saveBlock, new DataflowLinkOptions { PropagateCompletion = true });
saveBlock.LinkTo(sendBlock, new DataflowLinkOptions { PropagateCompletion = true });
Parallel.For(0, 250, i => readGenerateBlock.Post(i));
readGenerateBlock.Complete();
sendBlock.Completion.Wait();
Console.WriteLine("Completed.");
推荐答案
您必须先从数据块中读取数据,然后才能完成数据.由于noöne正在读取saveBlock
,因此它将永远不会完成.
You have to read the data out of the block before it will be completed. Since noöne is reading saveBlock
, it will never be completed.
如果不需要数据,最简单的解决方案是使用ActionBlock
而不是TransformBlock
.否则,只要继续读取数据,直到完成该块即可.
If you don't need the data, the easiest solution is to use ActionBlock
instead of TransformBlock
. Otherwise, just keep reading the data until the block is completed.
这篇关于C#TPL数据流-完成不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!