c# - 一个 ActionBlock 可以链接到另一个包含更多参数的 ActionBlock 吗?

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

我仍在掌握 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/

相关文章:

c# - 在以排队方式执行 cpu 绑定(bind)作业时避免线程池饥饿的策略

concurrency - 文件服务器 erlang 响应

java - Java 中使用堆栈的生产者-消费者

c# - Parallel.ForEach 与 Task.Factory.StartNew

javascript - 从代码隐藏中打开确认对话框

c# - 从不可变对象(immutable对象)设置拷贝是否可以避免线程损坏?

c# - 获取相关实体 ASP.NET WebApi OData v4 结果为 "No HTTP resource was found that matches the request URI"

java - LRU缓存的并发版本

c# - 如何在 C# 中对永无休止的任务最好地实现看门狗?

c# - 线程池会不会排队一个定时器的回调函数,有时会同时调度多个线程?