I was wondering if there are benefits associated with using a BufferBlock linked to one or many ActionBlocks, other than throttling (using BoundedCapacity), instead of just post
To add to svick's answer, there is another benefit of bufferblocks. If you have a block with multiple output links and want to balance between them, you have to turn the output blocks to bounded capacity of 1 and add a bufferblock to handle the queueing.
This is what we are planning to do:
Note, that BufferBlock does not handover copies of the input data to all the target blocks it is linked to. Instead it does so to one target block only.Here we are expecting that when one target is busy processing the request.It will be handed over to the other target.Now let’s refer to the code below:
static void Main(string[] args)
{
BufferBlock bb = new BufferBlock();
ActionBlock a1 = new ActionBlock(a =>
{
Thread.Sleep(100);
Console.WriteLine("Action A1 executing with value {0}", a);
});
ActionBlock a2 = new ActionBlock(a =>
{
Thread.Sleep(50);
Console.WriteLine("Action A2 executing with value {0}", a);
});
ActionBlock a3 = new ActionBlock(a =>
{
Thread.Sleep(50);
Console.WriteLine("Action A3 executing with value {0}", a);
});
bb.LinkTo(a1);
bb.LinkTo(a2);
bb.LinkTo(a3);
Task t = new Task(() =>
{
int i = 0;
while (i < 10)
{
Thread.Sleep(50);
i++;
bb.Post(i);
}
}
);
t.Start();
Console.Read();
}
When executed it produces the following output:
This shows that only one target is actually executing all the data even when it’s busy(due to the Thread.Sleep(100) added purposefully).Why?
This is because all the target blocks are by default greedy in nature and buffers the input even when they are not able to process the data. To change this behavior we have set the Bounded Capacity to 1 in the DataFlowBlockOptions while initializing the ActionBlock as shown below.
static void Main(string[] args)
{
BufferBlock bb = new BufferBlock();
ActionBlock a1 = new ActionBlock(a =>
{
Thread.Sleep(100);
Console.WriteLine("Action A1 executing with value {0}", a);
}
, new ExecutionDataflowBlockOptions {BoundedCapacity = 1});
ActionBlock a2 = new ActionBlock(a =>
{
Thread.Sleep(50);
Console.WriteLine("Action A2 executing with value {0}", a);
}
, new ExecutionDataflowBlockOptions {BoundedCapacity = 1});
ActionBlock a3 = new ActionBlock(a =>
{
Thread.Sleep(50);
Console.WriteLine("Action A3 executing with value {0}", a);
}
, new ExecutionDataflowBlockOptions {BoundedCapacity = 1});
bb.LinkTo(a1);
bb.LinkTo(a2);
bb.LinkTo(a3);
Task t = new Task(() =>
{
int i = 0;
while (i < 10)
{
Thread.Sleep(50);
i++;
bb.Post(i);
}
});
t.Start();
Console.Read();
}
The output of this program is:
This clearly a distribution of the data across three ActionBlock(s) as expected.