Implementing a concurrent producer/consumer pattern with the .NET BlockingCollection<T> class
Posted: (EET/GMT+2)
I recently needed to implement the producer/consumer pattern in my C# application, and the solution needed to support multiple threads. The .NET Framework contains great support for many needs, and it turns out the BlockingCollection<T> class in the System.Collections.Concurrent namespace already implements what I need.
The class is very useful for these scenarios, because it supports multi-threaded access, but also something called bounding. Bounding lets you set the maximum size for the collection. Thus, if a producer adds too many items to the collection before the consumer can process them, the bounding limits the amount of memory consumed by the collection as a whole.
If you are looking for a built-in class in .NET for similar purposes, be sure to check out BlockingCollection.
Happy hacking!