是否存在不接受输入但返回输出的TPL数据流块? [英] Is there a TPL dataflow block that doesn't take input but returns output?

查看:69
本文介绍了是否存在不接受输入但返回输出的TPL数据流块?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的问题的标题说明了一切.

The title of my question says it all.

我正在寻找不需要输入的TPL数据流块.

I am looking for a TPL dataflow block that doesn't need an input.

现在我正在使用转换块,但是它的输入尚未使用.

Right now I am using a transform block but it's input is unused.

推荐答案

我将从BufferBlock<T>构建这样的块:该方法接受代表该块ITargetBlock<T>端的委托并返回侧面.这样,委托可以将输入发送到该块,但是从外部看,它看起来像一个仅产生输出的块.

I would build a block like this from a BufferBlock<T>: the method accepts a delegate that presents the ITargetBlock<T> side of the block and returns the ISourceBlock<T> side of it. This way, the delegate can send input to the block, but from the outside, it looks like a block that only produces output.

代码:

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);

这篇关于是否存在不接受输入但返回输出的TPL数据流块?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆