Search code examples
c#parallel-processingtask-parallel-librarytpl-dataflow

How to call TriggerBatch automagically after a timeout if the number of queued items is less than the BatchSize?


Using Dataflow CTP (in the TPL)

Is there a way to call BatchBlock.TriggerBatch automatically if the number of currently queued or postponed items is less than the BatchSize, after a timeout?

And better: this timeout should be reset to 0 each time the block receives a new item.


Solution

  • Yes, you can accomplish this rather elegantly by chaining together blocks. In this case you want to setup a TransformBlock which you link "before" the BatchBlock. That would look something like this:

    Timer triggerBatchTimer = new Timer(() => yourBatchBlock.TriggerBatch());
    
    TransformBlock<T, T> timeoutTransformBlock = new TransformBlock<T, T>((value) =>
    {
        triggerBatchTimer.Change(5000, Timeout.Infinite);
    
        return value; 
    });
    
    timeoutTransformBlock.LinkTo(yourBatchBlock);
    
    yourBufferBlock.LinkTo(timeoutTransformBlock);