Search code examples
c#.nettask-parallel-librarytpl-dataflow

Completing a TPL dataflow chain


Given this code:

s_Batch = new BatchBlock<PerformanceRecord>(500);
s_Action = new ActionBlock<PerformanceRecord[]>(a => SendToDatabase(a));
s_Batch.LinkTo(s_Action);

When I'm done do I need to call Complete() on each block? Or will completing s_Batch trigger a complete in the blocks linked to it?


Solution

  • As your code stands now, you need to call Complete on all blocks individually:

    s_Batch.Complete();
    await s_Batch.Completion;
    
    s_Action.Complete();
    await s_Action.Completion;
    

    You could however use DataflowLinkOptions while linking the blocks to request completion propagation:

    s_Batch.LinkTo(s_Action, new DataflowLinkOptions {PropagateCompletion = true});
    s_Batch.Complete();
    await s_Batch.Completion;
    

    This will propagate both completion and faulting notification to the linked target block (i.e. s_Action).