【问题标题】:TPL Dataflow never completes when using a predicate使用谓词时,TPL 数据流永远不会完成
【发布时间】:2017-11-23 12:05:26
【问题描述】:

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

如果谓词对任何项目返回 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

【问题讨论】:

    标签: tpl-dataflow


    【解决方案1】:

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

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

    【讨论】:

      猜你喜欢
      • 2015-09-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多