Completing a TPL dataflow chain

岁酱吖の 提交于 2019-12-08 03:54:58

问题


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?


回答1:


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).




回答2:


I like l3arnon's answer actually since it is the most concise.

This is something else I have done/seen with TPL blocks which also works.

s_Batch.Completion.ContinueWith( t => 
    { 
        if(t.IsFaulted) 
            ((IDataFlowBlock)s_Action).Fault(t.Exception);
        else
            s_Action.Complete();
    });
s_Batch.Complete();
s_Action.Completion.Wait();

Downside is that you will need to repeat this pattern for each linked block so you end up repeating yourself quite a bit.



来源:https://stackoverflow.com/questions/26795126/completing-a-tpl-dataflow-chain

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!