Search code examples
c#.nettask-parallel-librarytpl-dataflow

How can I branch logic in TPL Dataflow?


Im brand new to TPL dataflow so forgive me if this is a simple question.

I have an input buffer block that takes a base class. How can I branch from there to a block based on the derived type? So for example:

var inputBlock = new BufferBlock<EventBase>();
//if EventBase is Meeting then go to block X
//if EventBase is Appointment the go to block Y

Thanks!


Solution

  • You can send a predicate to the LinkTo method to distinguish between the items. You would however need to downcast from EventBase inside each block to use logic specific to that type:

    var inputBlock = new BufferBlock<EventBase>();
    var meetingBlock = new ActionBlock<EventBase>(
        eventBase =>
        {
            var meeting = eventBase as Meeting;
            //...
        });
    var appointmentBlock = new ActionBlock<EventBase>(
        eventBase =>
        {
            var appointment = eventBase as Appointment;
            //...
        });
    
    inputBlock.LinkTo(meetingBlock, eventBase => eventBase is Meeting);
    inputBlock.LinkTo(appointmentBlock, eventBase => eventBase is Appointment);
    

    But as Servy pointed out you should probably avoid that and design your types to support polymorphism.