gpt4 book ai didi

c# - TPL 数据流 : Flatten incoming collection to sequential items

转载 作者:太空狗 更新时间:2023-10-30 01:30:25 24 4
gpt4 key购买 nike

我正在使用 TPL 数据流构建应用程序。其实我有以下问题。我有一个变形 block var tfb1 = new TranformBlock<InMsg, IReadOnlyCollection<OutMsg>> .所以tfb1接收消息并创建一个输出消息列表。此输出消息列表应链接到路由器数据 block ,该数据 block 接收 OutMsg。作为输入(而不是 IReadOnlyCollection<OutMsg> )。

我怎样才能展平 IReadOnlyCollection这样包含的消息可以用作例如的输入。 TransformBlock<OutMsg, SomeOtherType> 形式的变换 block .是否可以通过 LinkTo()

谢谢

最佳答案

您可以使用 TransformManyBlock而不是 TransformMany压平任何 IEnumerable<T>结果,例如:

var flattenBlock = new TransformManyBlock<InMsg,OutMsg>(msg=>{
List<OutMsg> myResultList;
//Calculate some results
return myResultList;
});

这会将单独的 OutMsg 实例传递到下一个 block 。

您可以使用迭代器,以便立即传播单个消息:

  var flattenBlock = new TransformManyBlock<InMsg,OutMsg>(msg=>{
//Calculate some results
foreach(var item in someDbResults)
{
yield return item;
}
});

或者你可以将输入展平:

var flattenBlock = new TransformManyBlock<IEnumerable<OutMsg>,OutMsg>(items=>items);

您可以将此 block 链接到任何接受 OutMsg 的 block :

var block = new ActionBlock<OutMsg>(...);

flattenBlock.LinkTo(block);

您可以通过将谓词传递给 LinkTo路由消息.例如,如果您想将失败消息路由到日志 block ,您可以键入:

flattenBlock.LinkTo(logBlock,msg=>msg.HasError);
flattenBlock.LinkTo(happyBlock);

不匹配任何谓词的消息将卡在输出缓冲区中并阻止 block 完成。通过一个没有谓词的链接,您可以确保所有消息都将被处理

关于c# - TPL 数据流 : Flatten incoming collection to sequential items,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45190119/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com