I have an object that is expensive to create, which uses some unmanaged resources that must be explicitly freed when done with and so implement IDisposable(). I would like a ca
Disposable objects always need to have a clear owner who is responsible for disposing them. However, this is not always the object that created them. Furthermore, ownership can be transferred.
Realizing this, the solution becomes obvious. Don't dispose, recycle! You need not only a way to acquire a resource from the cache, but also a way to return it. At that point the cache is owner again, and can choose to retain the resource for future use or to dispose it.
public interface IDisposableItemCache : IDisposable
where T:IDisposable
{
///
/// Creates a new item, or fetches an available item from the cache.
///
///
/// Ownership of the item is transfered from the cache to the client.
/// The client is responsible for either disposing it at some point,
/// or transferring ownership back to the cache with
/// .
///
T AcquireItem();
///
/// Transfers ownership of the item back to the cache.
///
void Recycle(T item);
}
edit: I just noticed that this idea also exists in Spring, where it is called an object pool. Their BorrowObject
and ReturnObject
methods match the methods in my example.