none
How can I drop a message between linked blocks

    Question

  • How can I drop a message between a link. When dropping I don't want to break the link, so that followed messages can be flowed over the link. (It seems that a filter used with LinkTo would break the link.)

    Thanks in advance!

    Tuesday, November 06, 2012 8:12 AM

Answers

  • LinkTo with a predicate doesn't break the link, but without an alternative some messages may end up blocking the sourceblock.

    Consider the following example where we want to print all even numbers in a buffer:

    BufferBlock<Int32> buffer = new BufferBlock<Int32>();
    ActionBlock<Int32> writer = new ActionBlock<Int32>((n) => Console.WriteLine(n));
    
    foreach (var number in Enumerable.Range(0, 10))
    {
        buffer.Post(number);
    }
    
    buffer.LinkTo(writer, (i) => i % 2 == 0);
    buffer.LinkTo(DataflowBlock.NullTarget<Int32>());

    Without a proper fallback (last line, the link to NullTarget) the message containing value 1 will block. So just add a DataflowBlock.NullTarget<T> and that will drop messages for you.

    • Marked as answer by Jesse Qu Wednesday, November 07, 2012 1:27 PM
    Tuesday, November 06, 2012 11:54 AM

All replies

  • LinkTo with a predicate doesn't break the link, but without an alternative some messages may end up blocking the sourceblock.

    Consider the following example where we want to print all even numbers in a buffer:

    BufferBlock<Int32> buffer = new BufferBlock<Int32>();
    ActionBlock<Int32> writer = new ActionBlock<Int32>((n) => Console.WriteLine(n));
    
    foreach (var number in Enumerable.Range(0, 10))
    {
        buffer.Post(number);
    }
    
    buffer.LinkTo(writer, (i) => i % 2 == 0);
    buffer.LinkTo(DataflowBlock.NullTarget<Int32>());

    Without a proper fallback (last line, the link to NullTarget) the message containing value 1 will block. So just add a DataflowBlock.NullTarget<T> and that will drop messages for you.

    • Marked as answer by Jesse Qu Wednesday, November 07, 2012 1:27 PM
    Tuesday, November 06, 2012 11:54 AM
  • Thanks Lasagna!

    I tried. What you anwered works.

    Wednesday, November 07, 2012 1:26 PM