Exercise: Generic Producer-Consumer framework

I assume that you have done the exercise Producer-Consumer using BlockingCollection.

In the original version Producers and Consumers could only use int's.

In this exercise you must make a new version of the Producer, Consumer, etc. so that they become generic - and will be able to handle any type (not just int).

Getting ready

  1. Make sure you have done theexercise Producer-Consumer using BlockingCollection.
  2. Create a new Solution in Visual Studio. Name the new solution "ProducerConsumerGeneric"

Producer

Create a class Producer. The class must be generic (Producer<T>).

The class must use BlockingCollection as the type of the buffer to add to.

The Producer should do Console.WriteLine(...) every time an element has been added to the buffer.

Problem

The Producer probably uses an ordinary for loop, however the indexes from the for loop can not be used as a parameter to buffer.Add(...), which wants an object of type T (the generic type parameter).

Solution: Delegate the problem to another object

Create an interface IElementFactory, and add an object of this type as a parameter to the Producers constructor.

Consumer

Create a class Consumer. The class must be generic (Consumer<T>).

Main

  1. Make a class that implements the interface IElementFactory, for example StringFactory
  2. 1 buffer + 1 producer + 1 consumer. Use Parallel.Invoke(...)
  3. 1 buffer + 1 producer + 2 consumers. Use Parallel.Invoke(...)

MiddleMan

Create a class MiddleMan. The class must be generic (MiddleMan<T>).

Main

MiddleMan2: More flexibility

The ordinary MiddleMan uses the same type <T> for the ingoing and the outgoing buffers.

Now you are going to make another (and more flexible) class MiddleMan2 which can use different (but related) types for the ingoing and the outgoing buffer.

Create a class MiddleMan2. The class must be generic: MiddleMan2<TIn, TOut> where TIn : TOut { ... }

Main

  1. 2 buffers (of the same type) + 1 producer + 1 middleman + 1 consumer. Use Parallel.Invoke(...)
  2. 2 buffers (of different types) + 1 producer + 1 middleman + 1 consumer. Use Parallel.Invoke(...)

Extra: Logging

Substitute all Console.WriteLine(...) with logging.