I don’t want to write my own because i’m afraid i might miss something and/or rip off other people’s work, so is there an ObjectPool (or similar) class existing in a library for .NET?
By object pool, i mean a class that assists caching of objects that take a long time to create, generally used to improve performance.
UPDATE:
I’d also put forward
BufferBlock<T>from TPL DataFlow. IIRC it’s part of .net now. The great thing aboutBufferBlock<T>is that you can wait asynchronously for items to become available using thePost<T>andReceiveAsync<T>extension methods. Pretty handy in an async/await world.ORIGINAL ANSWER
A while back I faced this problem and came up with a lightweight (rough’n’ready) threadsafe (I hope) pool that has proved very useful, reusable and robust:
In order to avoid any interface requirements of the pooled objects, both the creation and resetting of the objects is performed by user supplied delegates: i.e.
In the case that the pool is empty, the BeginPop/EndPop pair provide an APM (ish) means of retrieving the object asynchronously when one becomes available (using Jeff Richter’s excellent AsyncResult<TResult> implementation).
I can’t quite remember why it is constained to T : class… there’s probably none.