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!
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With