.NET 4.5 Baby Steps, Part 5: Some more interesting blocks

Other posts in this series can be found on the Series Index Page

Introduction

We have seen the IDataFlowBlock, in three different implementations, and now we will look at a few more.

BroadcastBlock

In the BatchBlock we saw that if you had multiple subscribers, messages are delivered to subscribers in a round-robin way. But what if you want to send the same message to all subscribers? The solution is the BroadcastBlock<T>.

static BroadcastBlock<string> pubSub = new BroadcastBlock<string>(s =>
{
    return s + " relayed from publisher";
});

static async void Process()
{
    var message = await pubSub.ReceiveAsync();
    Console.WriteLine(message);
}

static void Main(string[] args)
{
    // setup 5 subscribers
    for (int i = 0; i < 5; i++)
    {
        Process();
    }

    pubSub.Post(DateTime.Now.ToLongTimeString());

    Console.ReadLine();
}

TransformBlock<TInput,TOutput>

The next interesting block is the transform block, which works similarly to the action block, except that the input and output can be different types. So we can transform the data internally.

static TransformBlock<int, string> pubSub = new TransformBlock<int, string>(i =>
{
    return string.Format("we got: {0}", i);
});

static async void Process()
{
    while (true)
    {
        var message = await pubSub.ReceiveAsync();
        Console.WriteLine(message);
    }
}

static void Main(string[] args)
{
    Process();

    for (int i = 0; i < 10; i++)
    {
        pubSub.Post(i);
        Thread.Sleep(1000);
    }

    Console.ReadLine();
}

Attachments