Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 424
jmichas Avatar asked Sep 02 '14 14:09

jmichas


2 Answers

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.

like image 152
i3arnon Avatar answered Nov 03 '22 17:11

i3arnon


If you want a simpler solution and don't mind using a helper library built upon TPL Dataflow, there is DataflowEx which provides a LinkSubTypeTo() method.

Dataflow<TIn, TOut> flow1;
Dataflow<TOutSubType1> flow2;
Dataflow<TOutSubType2> flow3;

flow1.LinkSubTypeTo(flow2);
flow1.LinkSubTypeTo(flow3);

Please check the advanced linking section of the library's document. Internally it uses the same mechanism @I3arnon introduced.

Disclaimer: I am the author of DataflowEx.

like image 43
Dodd Avatar answered Nov 03 '22 19:11

Dodd