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 cache for instance of these expensive resources so that the creation cost is minimized, but I am having trouble knowing how to deal with the disposal.
If the methods that use the objects are responsible for the disposal then I end up with disposed instances in the cache, which then have to be recreated, defeating the point of the cache. If I don't dispose the objects in the methods that use them then they never get disposed. I thought I could dispose them when they are taken out of the cache, but then I might end up disposing an instance which is still being used by a method.
Is it valid to just let them go out of scope and be collected by the garbage collector and free up the resources at that point? This feels wrong and against the idea of them being disposable...
Answer
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.
No comments:
Post a Comment