Home > Development > Producer Consumer Scenarios with BlockingCollection

Producer Consumer Scenarios with BlockingCollection


Producer Consumer is really easy with TPL. You create a blocking collection and one task(producer) uses Add() to add items to it and another task(consumer) reads data from it using TryTake().

The consumer must signal to the consumers that it has finished adding by calling CompleteAdding().

using System.Linq;
using System.Text;
using System.Collections.Concurrent;
using System.Threading.Tasks;
using System.Threading;

namespace BlockingCollectionSample
{
    public class Program
    {
        static void Main(string[] args)
        {
            Program p = new Program();
            p.TestingBlockingCollection();

            Console.WriteLine("Press any key to quit..");
            Console.ReadKey();
        }

        public void TestingBlockingCollection()
        {

            BlockingCollection<string> collection = new BlockingCollection<string>();

            var p = Task.Factory.StartNew(() =>
            {
                Random r = new Random();
                for (int i = 0; i < 5; i++)
                {
                    Thread.Sleep(1000);
                    int value = r.Next(100);
                    Console.WriteLine("Task {0} produced value {1}", Task.CurrentId, value);
                    collection.Add(value.ToString());
                }
                collection.CompleteAdding();

            });

            var c = Task.Factory.StartNew(() =>
            {
                Task.Factory.StartNew(() =>
                {
                    while (!collection.IsCompleted)
                    {
                        string value = null;
                        collection.TryTake(out value);

                        if (value != null)
                        {
                            Console.WriteLine("Task {0} consumed value {1}", Task.CurrentId, value);
                        }
                    }

                },TaskCreationOptions.AttachedToParent);

                Task.Factory.StartNew(() =>
                {
                    while (!collection.IsCompleted)
                    {
                        
                        string value = null;
                        collection.TryTake(out value);

                        if (value != null)
                        {
                            Console.WriteLine("Task {0} consumed value {1}", Task.CurrentId, value);
                        }
                    }

                }, TaskCreationOptions.AttachedToParent);

            });
            Task.WaitAll(p, c);
        }
    }
}

Could also be coded like the following:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections.Concurrent;
using System.Threading.Tasks;
using System.Threading;

namespace BlockingCollectionSample
{
    public class Program
    {
        static void Main(string[] args)
        {
            Program p = new Program();
            p.TestingBlockingCollection();

            Console.WriteLine("Press any key to quit..");
            Console.ReadKey();
        }

        public void TestingBlockingCollection()
        {

            BlockingCollection collection = new BlockingCollection();

            var p = Task.Factory.StartNew(() =&gt;
            {
                Random r = new Random();
                for (int i = 0; i 
            {
                Parallel.ForEach(collection.GetConsumingEnumerable(), x =&gt;
                {
                    Console.WriteLine("Consumer processed: {0}", x);
                });
            });

            Task.WaitAll(p, c);

        }


    }
}
Advertisements
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: