我仍在掌握 TPL DataFlow,所以请耐心等待。
我的应用程序要求并行执行队列,同时保留其顺序。这让我找到了 DataFlow 库以及我正在尝试做的事情。我想知道是否有一种方法可以将一个 ActionBlock 链接到另一个 ActionBlock,而第二个 ActionBlock 则从第一个 ActionBlock 获取值进行操作。
伪示例:
var block1 = new ActionBlock<ByteBuffer>(buffer => {
// code generating a hash of the byte buffer to pass to next block
ulong hash = generateHash(buffer);
// this is what i would like to pass to the next ActionBlock
var tup = Tuple<ByteBuffer, ulong>(buffer, along);
}, dataFlowOpts);
var block2 = new ActionBlock<Tuple<ByteBuffer, ulong>(tup => {
/* code to act on the buffer and hash */
}, dataFlowOpts);
block1.LinkTo(block2); // Is there something like this that would use the correct params?
我想做的事情可能吗?这还有道理吗?我将它们分成两个 ActionBlocks
的原因是我想在另一个代码路径中重用 block2(以不同的方式散列不同 ByteBuffer
的内容。)
也许有更好的方法?实际上,我只是尝试对以并发方式传入的对象进行哈希处理,同时保留 FIFO 顺序,因为同步对这些对象进行哈希处理太慢了。
最佳答案
只需使用TransformBlock
:
var block1 = new TransformBlock<ByteBuffer, Tuple<ByteBuffer, ulong>>(buffer => {
// code generating a hash of the byte buffer to pass to next block
ulong hash = generateHash(buffer);
// this is what i would like to pass to the next ActionBlock
return Tuple<ByteBuffer, ulong>(buffer, along);
}, dataFlowOpts);
var block2 = new ActionBlock<Tuple<ByteBuffer, ulong>(tup => {
/* code to act on the buffer and hash */
}, dataFlowOpts);
block1.LinkTo(block2); // Is there something like this that would use the correct params?
或者,使用具有两个属性的 DTO 类可能是更好的选择:缓冲区和哈希,因为 Tuple
的可读性不太好。另外,请考虑有关命名元组的新 C# 功能。
关于c# - 一个 ActionBlock 可以链接到另一个包含更多参数的 ActionBlock 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44402743/