TPL数据流CompletionPropagation不起作用MaxMessage-选项不起作用

时间:2019-01-22 16:24:46

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

我已经检查了该帖子: C# TPL Dataflow - Completion not working(但在此处添加NullTarget不会改变结果)

还有一些。

但是我不明白为什么这个例子没有完成:

private static async Task WriteIntDelayed(int delay_ms, string name, int? i)
{
    await Task.Delay(delay_ms);
    await Console.Out.WriteLineAsync(name + "\t" + (i.HasValue ? i.ToString() : "null"));
}
private static int counter = 0;
public static async Task ExecuteMultipleSuccessorsSampleAsync()
{
    TransformBlock<string, int?> tb = new TransformBlock<string, int?>(
                s =>
                {
                    if (Int32.TryParse(s, out int result))
                    {
                        return result;
                    }
                    else
                        return null;
                });

    ActionBlock<int?> ab1 = new ActionBlock<int?>(async (int? i) => await WriteIntDelayed(10, $"ab1[{counter++}]", i));
    ActionBlock<int?> ab2 = new ActionBlock<int?>(
        async (int? i)
            => await WriteIntDelayed(500, $"ab2[{counter++}]", i)
        , new ExecutionDataflowBlockOptions { BoundedCapacity = 1 });
    ActionBlock<int?> ab3 = new ActionBlock<int?>(
        async (int? i)
            => await WriteIntDelayed(200, $"ab3[{counter++}]", i),
        new ExecutionDataflowBlockOptions { BoundedCapacity = 1 });

    tb.LinkTo(ab1, new DataflowLinkOptions { MaxMessages = 10, PropagateCompletion = true });
    tb.LinkTo(ab2, new DataflowLinkOptions { PropagateCompletion = true });
    tb.LinkTo(ab3, new DataflowLinkOptions { PropagateCompletion = true });


    // Parallel.For(0, 30, (i, state) =>
    // {
    //     tb.Post(i.ToString());
    // });

    for (int i = 0; i < 30; i++)
    {
        tb.Post(i.ToString());
    }

    tb.Complete();
    await Task.WhenAll(
        ab1.Completion /*will NOT complete */, 
        ab2.Completion /*will complete */, 
        ab3.Completion /*will complete */);
}

0 个答案:

没有答案