Exercise: Producer-Consumer using BlockingCollection
In a previous exercise you made a Producer-Consumer framework with a BoundedBuffer (and an UnboundedBuffer).
In this exercise you must make another version of the Producer-Consumer framework, now using a BlockingCollection.
Depending on how you use BlockingCollection it can be bounded or unbounded.
Getting ready
Create a new Solution in Visual Studio. Name the Solution "ProducerConsumerBlockingCollection".
Producer
Create a class Producer.
The constructor must have 2 parameters
- BlockingCollection buffer
- int howMany (the number of items that this Producer must produce)
void Run() method
- for loop adding to the buffer.
- call Console.WriteLine(...) after adding each element
- After the for loop call buffer.CompletAdding()
Consumer
Create a class Consumer.
The constructor must have 1 parameter
- BlockingCollection buffer
void Run() method
- while loop running until buffer.IsComplete is false
- call Console.WriteLine(...) after taking each element
Main
- 1 buffer + 1 producer + 1 consumer. Use Parallel.Invoke(...)
- 1 buffer + 1 producer + 2 consumers. Use Parallel.Invoke(...)
- 1 buffer using either ConcurrentBag or ConcurrentStask as a constructor parameter + 1 producer + 1 consumer
MiddleMan
Create a class MiddleMan. The MiddleMan takes an element from one buffer and adds the element to another buffer.
The constructor must have 2 parameters
- BlockingCollection ingoingBuffer
- BlockingCollection outgoingBuffer
void Run() method
- while loop running until buffer.IsComplete is false
- call Console.WriteLine(...) after (take + add) each element
Main
- 2 buffers + 1 producer + 1 middleman + 1 consumer. Use Parallel.Invoke(...)
Extra: Logging
Substitute all Console.WriteLine(...) with logging.s