问题
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