是否有不接受输入但 returns 输出的 TPL 数据流块?
Is there a TPL dataflow block that doesn't take input but returns output?
我的问题标题说明了一切。
我正在寻找不需要输入的 TPL 数据流块。
现在我正在使用转换块,但它的输入未被使用。
我会从 BufferBlock<T>
构建一个这样的块:该方法接受一个代表块的 ITargetBlock<T>
侧和 returns ISourceBlock<T>
侧的委托它的。这样,委托可以向块发送输入,但从外部看,它看起来像一个只产生输出的块。
代码:
public static ISourceBlock<T> CreateProducerBlock<T>(
Func<ITargetBlock<T>, Task> producer,
int boundedCapacity = DataflowBlockOptions.Unbounded)
{
var block = new BufferBlock<T>(
new ExecutionDataflowBlockOptions { BoundedCapacity = boundedCapacity });
Task.Run(async () =>
{
try
{
await producer(block);
block.Complete();
}
catch (Exception ex)
{
((IDataflowBlock)block).Fault(ex);
}
});
return block;
}
用法示例:
var producer = CreateProducerBlock<int>(async target =>
{
await target.SendAsync(10);
await target.SendAsync(20);
});
ITargetBlock<int> consumer = …;
producer.LinkTo(consumer);
有时最简单的方法是使用一次性 bool
作为 TransformManyBlock 的输入,然后 .Post(true)
启动您的管道。
我的问题标题说明了一切。
我正在寻找不需要输入的 TPL 数据流块。
现在我正在使用转换块,但它的输入未被使用。
我会从 BufferBlock<T>
构建一个这样的块:该方法接受一个代表块的 ITargetBlock<T>
侧和 returns ISourceBlock<T>
侧的委托它的。这样,委托可以向块发送输入,但从外部看,它看起来像一个只产生输出的块。
代码:
public static ISourceBlock<T> CreateProducerBlock<T>(
Func<ITargetBlock<T>, Task> producer,
int boundedCapacity = DataflowBlockOptions.Unbounded)
{
var block = new BufferBlock<T>(
new ExecutionDataflowBlockOptions { BoundedCapacity = boundedCapacity });
Task.Run(async () =>
{
try
{
await producer(block);
block.Complete();
}
catch (Exception ex)
{
((IDataflowBlock)block).Fault(ex);
}
});
return block;
}
用法示例:
var producer = CreateProducerBlock<int>(async target =>
{
await target.SendAsync(10);
await target.SendAsync(20);
});
ITargetBlock<int> consumer = …;
producer.LinkTo(consumer);
有时最简单的方法是使用一次性 bool
作为 TransformManyBlock 的输入,然后 .Post(true)
启动您的管道。