Implement a Parallel Producer-Consumer Pattern - CSharp Thread Asynchronous

CSharp examples for Thread Asynchronous:Producer Consumer

Description

Implement a Parallel Producer-Consumer Pattern

Demo Code


using System;/* w w w  . j av a2 s.  c  o  m*/
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections.Concurrent;
using System.Threading.Tasks;

class MainClass
    {
        static void Main(string[] args)
        {
            BlockingCollection<string> bCollection = new BlockingCollection<string>(new ConcurrentQueue<string>(), 3);

            Task consumerTask = Task.Factory.StartNew(() => performConsumerTasks(bCollection));

            Task producer0 = Task.Factory.StartNew(() => performProducerTasks(bCollection, 0));
            Task producer1 = Task.Factory.StartNew(() => performProducerTasks(bCollection, 1));
            Task producer2 = Task.Factory.StartNew(() => performProducerTasks(bCollection, 2));
            Task producer3 = Task.Factory.StartNew(() => performProducerTasks(bCollection, 3));

            Task.WaitAll(producer0, producer1, producer2, producer3);
            Console.WriteLine("Producer tasks complete.");

            bCollection.CompleteAdding();

            // wait for the consumer task to complete
            consumerTask.Wait();
        }

        static void performConsumerTasks(BlockingCollection<string> collection)
        {
            Console.WriteLine("Consumer started");
            foreach (string collData in collection.GetConsumingEnumerable())
            {
                // write out the data
                Console.WriteLine("Consumer got message {0}", collData);
            }
            Console.WriteLine("Consumer completed");
        }

        static void performProducerTasks(BlockingCollection<string> collection, int taskID)
        {
            Console.WriteLine("Producer started");
            for (int i = 0; i < 100; i++)
            {
                // put something into the collection
                collection.Add("TaskID " + taskID + " Message" + i++);
                Console.WriteLine("Task {0} wrote message {1}", taskID, i);
            }
        }
    }

Result


Related Tutorials