C TPL数据流BatchBlock等待完成,永不返回

时间:2018-11-16 21:07:59

标签: c# tpl-dataflow

我创建了一个小型测试程序来说明我的问题

class Item
{
    public string Name;
}

class Program
{
    static BatchBlock<Item> items = new BatchBlock<Item>(2);
    static ConcurrentBag<Item> bag = new ConcurrentBag<Item>();

    public static async Task Main(string[] args)
    {
        var insertItems = new ActionBlock<Item[]>(b => BatchProcessor(b));
        items.LinkTo(insertItems);
        var finished = items.Completion.ContinueWith(delegate { insertItems.Complete(); }).ConfigureAwait(false);

        Console.WriteLine("From main 1");
        items.Post(new Item() { Name = "1" });

        Console.WriteLine("From main 2");
        items.Post(new Item() { Name = "2" });

        Console.WriteLine("From main 3");
        items.Post(new Item() { Name = "3" });

        Console.WriteLine("From main 4");
        items.Post(new Item() { Name = "4" });

        Console.WriteLine("From main 5");
        items.Post(new Item() { Name = "5" });

        Console.WriteLine("From main 6");
        items.Post(new Item() { Name = "6" });

        Console.WriteLine("From main 7");
        items.Post(new Item() { Name = "7" });

        Console.WriteLine("Finishing");
        items.TriggerBatch();

        await items.Completion; // Never completes!!!
    }

    static void BatchProcessor(Item[] items)
    {
        Console.WriteLine("Callback");
        foreach(var i in items)
        {
            Console.WriteLine("From Callback " + i.Name);
            bag.Add(i);
        }
    }
}

控制台输出符合预期:

From main 1
From main 2
From main 3
From main 4
From main 5
From main 6
From main 7
Finishing
Callback
From Callback 1
From Callback 2
Callback
From Callback 3
From Callback 4
Callback
From Callback 5
From Callback 6
Callback
From Callback 7

我想念什么?

1 个答案:

答案 0 :(得分:5)

完成向块的数据发送后,您需要调用Complete

此:

await items.Completion;

为了等待整个流程完成,实际上应该是:

items.Complete()
await insertItems.Completion;

最后,您可以链接块以传播完成,因此在这种情况下ContinueWith是不必要的。

此:

items.Completion.ContinueWith(delegate { insertItems.Complete(); }).ConfigureAwait(false);

可以替换为:

items.LinkTo(insertItems, new DataflowLinkOptions() { PropagateCompletion = true });