Home:ALL Converter>Why is my ActionBlock not executed when my BroadcastBlock posts?

Why is my ActionBlock not executed when my BroadcastBlock posts?

Ask Time:2018-06-08T21:59:57         Author:TJ Rockefeller

Json Formatter

I am trying to understand Dataflow in C#, so I wrote a fiddle here and I'm curious why my action blocks are not executing in my example.

using System;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using System.Threading.Tasks.Dataflow;

public class Program
{
    public static void Main(string[] args)
    {
        var numberOfProducers = 1;
        var numberOfConsumers = 10;
        
        var allProducers = Enumerable.Range(0, numberOfProducers).Select(x => new BroadcastBlock<double>(d =>
            {
                return d;
            },
            new DataflowBlockOptions()
            {
                BoundedCapacity = 500
            }));
        
        var allConsumers = Enumerable.Range(0, numberOfConsumers).Select(x => new ActionBlock<double>(d =>
            {
                Console.WriteLine(String.Format("Consuming {0} on Thread ID: {1}", d, Thread.CurrentThread.ManagedThreadId));
            },
            new ExecutionDataflowBlockOptions()
            {
                BoundedCapacity = 500
            }));
        
        foreach (var producer in allProducers)
        {
            foreach (var consumer in allConsumers)
            {
                producer.LinkTo(consumer);
            }
        }

        Parallel.For(0, 20, (i) =>
        {
            foreach (var producer in allProducers)
            {
                Console.WriteLine(String.Format("Posting {0} on Thread ID: {1}", i, Thread.CurrentThread.ManagedThreadId));
                producer.Post(i);
            }
        }

        );
    }
}

An example of output from this program is as follows

Posting 0 on Thread ID: 18

Posting 10 on Thread ID: 16

Posting 1 on Thread ID: 17

Posting 11 on Thread ID: 19

Posting 2 on Thread ID: 18

Posting 4 on Thread ID: 17

Posting 5 on Thread ID: 17

Posting 6 on Thread ID: 17

Posting 3 on Thread ID: 18

Posting 12 on Thread ID: 18

Posting 7 on Thread ID: 17

Posting 16 on Thread ID: 19

Posting 8 on Thread ID: 17

Posting 17 on Thread ID: 19

Posting 9 on Thread ID: 17

Posting 18 on Thread ID: 19

Posting 19 on Thread ID: 19

Posting 13 on Thread ID: 18

Posting 14 on Thread ID: 18

Posting 15 on Thread ID: 18

I would expect there to be several lines mixed in showing the action blocks consuming the data being posted on the broadcast block.

Author:TJ Rockefeller,eproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/50762336/why-is-my-actionblock-not-executed-when-my-broadcastblock-posts
yy