How can I fork logic in a TPL data stream?

I'm new to TPL dataflow, so forgive me if this is a simple question.

I have an input buffer block that a base class takes. How can I go from there to a block based on a derived type? 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

      

Thank!

+3


source to share


2 answers


You can send a predicate to a method LinkTo

to differentiate between elements. However, you will need to disable EventBase

inside each block in order 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 said, you should probably avoid this and create your types to support polymorphism.

+5


source


If you want a simpler solution and don't mind using a helper library built on TPL dataflow , DataflowEx , which provides the LinkSubTypeTo () Method.

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

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

      



Please see the extended link section in the library document. Internally, it uses the same @ I3arnon mechanism.

Disclaimer: I am the author of DataflowEx .

+1


source







All Articles