使用谓词时 TPL 数据流永远不会完成

Jas*_*ker 3 tpl-dataflow

我有以下 TPL 数据流,当使用谓词过滤从 TransformBlock 传递到 ActionBlock 的项目时,它永远不会完成。

如果谓词对任何项目返回 false,则数据流挂起。

请有人提供一些关于发生了什么以及如何解决这个问题的见解?

// define blocks 
var getBlock = new TransformBlock<int, int>(i =>
{
    Console.WriteLine($"getBlock: {i}");

    return ++i;
});

var writeBlock = new ActionBlock<int>(i =>
{
    Console.WriteLine($"writeBlock: {i}");
});

// link blocks
getBlock.LinkTo(writeBlock, new DataflowLinkOptions
{
    PropagateCompletion = true
}, i => i == 12); // <-- this predicate prevents the completion of writeBlock

// push to block 
var items = new List<int> { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
foreach (var i in items)
{
    getBlock.Post(i); 
}

// wait for all operations to complete
getBlock.Complete();
await writeBlock.Completion; // <-- application hangs here
Run Code Online (Sandbox Code Playgroud)

JSt*_*ard 6

getBlock没有完成,因为项目发布到它无处可去。如果您有一个谓词,请添加一个空目标,以便任何不匹配的项目都有一个地方可以退出管道。

getBlock.LinkTo(writeBlock, new DataflowLinkOptions
{
    PropagateCompletion = true
}, i => i == 12)
getBlock.LinkTo(DataflowBlock.NullTarget<int>());
Run Code Online (Sandbox Code Playgroud)