TPL数据流:为什么以下阻止?

时间:2019-01-25 17:07:55

标签: c# task-parallel-library tpl-dataflow

为什么调用Run()阻止并且不返回?

正确打印以下输出,这很有意义。当我初始化大小为170的BatchBlock()并创建200个volapoint对象时。但是为什么它不返回?

ConvertToVolaSurface 
ConvertToVolaSurface 
CalculateStrangles
CalculateStrangles

这是我正在使用的代码段

class Pipeline
{
    public void Run()
    {
        // Grouping block - Collect vola points until vola surface is full 
        var batchBlock1 = new BatchBlock<VolaPoint>(170);

        // Execution block - Convert vola points to surface
        var transformBlock0 = new TransformBlock<VolaPoint[], VolaSurface>(x => this.ConvertToVolaSurface(x));

        // Execution block - Calculate strangles 
        var transformBlock1 = new TransformBlock<VolaSurface, VolaSurface>(x => this.CalculateStrangles(x));

        var linkOptions = new DataflowLinkOptions()
        {
            PropagateCompletion = true
        };

        batchBlock1.LinkTo(transformBlock0, linkOptions);
        transformBlock0.LinkTo(transformBlock1, linkOptions);

        for (int i = 0; i <= 200; i++)
        {
            batchBlock1.Post(new VolaPoint());
        }

        batchBlock1.Complete();

        transformBlock1.Completion.Wait();
    }

    private VolaSurface ConvertToVolaSurface(VolaPoint[] volapoints)
    {
        Debug.WriteLine("ConvertToVolaSurface");

        return new VolaSurface();
    }

    private VolaSurface CalculateStrangles(VolaSurface volaSurface)
    {
        Debug.WriteLine("CalculateStrangles");

        return volaSurface;
    }
}   

1 个答案:

答案 0 :(得分:1)

您的最后一块是TransformBlock,变换块的输出缓冲区必须为Complete为空。将最后一个块更改为ActionBlock,然后await完成,不阻塞调用线程。

public async Task Run()
{
    // Grouping block - Collect vola points until vola surface is full 
    var batchBlock1 = new BatchBlock<VolaPoint>(170);

    // Execution block - Convert vola points to surface
    var transformBlock0 = new TransformBlock<VolaPoint[], VolaSurface>(x => this.ConvertToVolaSurface(x));

    // Execution block - Calculate strangles 
    var actionBlock1 = new ActionBlock<VolaSurface>(x => this.CalculateStrangles(x));

    var linkOptions = new DataflowLinkOptions()
    {
        PropagateCompletion = true
    };

    batchBlock1.LinkTo(transformBlock0, linkOptions);
    transformBlock0.LinkTo(actionBlock1, linkOptions);

    for (int i = 0; i <= 200; i++)
    {
        batchBlock1.Post(new VolaPoint());
    }

    batchBlock1.Complete();

    await actionBlock1.Completion;
}

现在,如果CalculateStrangles(x)返回的内容是,那么您需要将最后一个转换块链接到其他内容,否则您将永远无法完成。