How to use the object pool design pattern in C#


When building applications, you often come across objects that are quite expensive to create. In some scenarios, the cost of creating new objects is high enough to impact application performance. Here’s where the object pool design pattern comes to the rescue. 

The object pool design pattern is a creational design pattern that is used to recycle objects rather than recreate them each time the application needs them. By keeping reusable instances of objects in a resource pool, and doling them out as needed, this pattern helps to minimize the overhead of initializing, instantiating, and disposing of objects and to boost the performance of your application.

When the application requests an object, and the object is available from the pool, it is returned from the pool. If the object of the requested type is not available from the pool, then a new instance of the object is created and returned. When the application no longer needs the object, the object is sent back to the pool.

The minimum and maximum number of objects that an object pool can hold is configurable. If the application needs an object from the pool but the maximum number of objects has been allocated, a typical custom object pool implementation can adopt one or more of the following strategies: