我仍然对TPL DataFlow感兴趣,所以请耐心等待。
我的应用程序要求队列在保持其顺序的同时并行执行。这导致我进入DataFlow库以及我想要做的事情。我想知道是否有办法将一个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顺序,因为它太慢而无法同步散列这些对象。
答案 0 :(得分:2)
只需使用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#功能。