C# TransformBlock 在调用 Complete 函数后不执行

C# TransformBlock is not executed after calling Complete function

我有这个代码片段:

static void Main(string[] args)
{
    var printResult = new ActionBlock<int>(x =>
    {
        Console.WriteLine(x);
    });
    var countBytes = new TransformBlock<int, int>(
        new Func<int, int>((x)=> { return 2 * x; }));
    countBytes.LinkTo(printResult, new DataflowLinkOptions { PropagateCompletion = true });
    countBytes.Completion.ContinueWith(delegate { printResult.Complete(); });
    countBytes.Complete();
    printResult.Completion.Wait();
    Console.ReadKey();
}

我预计

TransformBlock 代码
return 2*x

会运行,然后打印结果,但实际上什么也没有打印。我在

里面设置了一个断点
printResult

Console.WriteLine 上的函数对象,但未介入。

为什么什么都没有打印出来,我哪里出错了,如何解决?

您缺少告诉 countBytes 将完成传播到链接块的设置(尝试使用 ContinueWith() 来完成链接块是执行此操作的错误方法)。

此外,如果您不向管道 post 添加任何内容,将不会有任何输出。

试试这个:

static void Main(string[] args)
{
    var printResult = new ActionBlock<int>(x =>
    {
        Console.WriteLine(x);
    });

    var countBytes = new TransformBlock<int, int>(new Func<int, int>((x) => { return 2 * x; }));

    countBytes.LinkTo(printResult, new DataflowLinkOptions { PropagateCompletion = true });
    countBytes.Post(1);
    countBytes.Completion.ContinueWith(task => Console.WriteLine("countBytes has completed"));
    printResult.Completion.ContinueWith(task => Console.WriteLine("printResult has completed"));
    countBytes.Complete();
    printResult.Completion.Wait();
    Console.WriteLine("Done");
    Console.ReadLine();
}

如果你运行那个,输出是:

2
countBytes has completed
Done
printResult has completed

(请注意 "printResult has completed" 如何在 "Done" 之后输出 。这是因为在 printResult.Completion 发出信号后安排继续。)

如果您像这样注释掉 new DataflowLinkOptions { PropagateCompletion = true }

countBytes.LinkTo(printResult /*, new DataflowLinkOptions { PropagateCompletion = true } */);

那么输出将是:

2
countBytes has completed

请注意,"Done" 不会打印,因为如果完成未传播到该块,printResult.Completion.Wait() 永远不会 returns。