I have a class that is expensive to construct, in terms of time and memory. I'd like to maintain a pool of these things and dispense them out on demand to multiple threads in the same process.
Is there a general-purpose object pool that is already tested and proven? (I don't want COM+ pooling.)
Pulled straight from MSDN, here's an example of using one of the new concurrent collection types in .NET 4:
The following example demonstrates how to implement an object pool with a
System.Collections.Concurrent.ConcurrentBag<T>
as its backing store.
public class ObjectPool<T>
{
private ConcurrentBag<T> _objects;
private Func<T> _objectGenerator;
public ObjectPool(Func<T> objectGenerator)
{
if (objectGenerator == null)
throw new ArgumentNullException("objectGenerator");
_objects = new ConcurrentBag<T>();
_objectGenerator = objectGenerator;
}
public T GetObject()
{
T item;
if (_objects.TryTake(out item))
return item;
return _objectGenerator();
}
public void PutObject(T item)
{
_objects.Add(item);
}
}