In this section, we will see how blocking collections work when there are multiple producer and consumer threads. For the sake of understanding, we will create two producers and one consumer. The producer threads will produce the items. Once all of the producer threads have called CompleteAdding, then the consumer will start reading items from the collection:
- Let's start by creating a blocking collection with multiple producers:
BlockingCollection<int>[] produceCollections = new BlockingCollection<int>[2];
produceCollections[0] = new BlockingCollection<int>(5);
produceCollections[1] = new BlockingCollection<int>(5);
- Next, we will create two producer tasks that will add items to the producers:
Task producerTask1 = Task.Factory.StartNew(() =>
{
for (int i = 1; i <= 5; ++i)
{
produceCollections...