【问题标题】:Can an ActionBlock link to another ActionBlock with more parameters in it?一个 ActionBlock 可以链接到另一个包含更多参数的 ActionBlock 吗?
【发布时间】:2017-06-07 02:53:57
【问题描述】:

我仍然对 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 顺序,因为同步散列这些对象太慢了。

【问题讨论】:

  • 您是否考虑过使用 Rx - Microsoft 的反应式框架? (NuGet“System.Reactive”)

标签: c# concurrency task-parallel-library .net-4.5 tpl-dataflow


【解决方案1】:

只需使用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# 功能。

【讨论】:

  • 现在看起来很明显!谢谢。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-09-20
  • 1970-01-01
  • 2011-01-10
  • 2021-11-20
  • 1970-01-01
相关资源
最近更新 更多