How to manage IDisposable Objects that are cached?

前端 未结 6 2085
囚心锁ツ
囚心锁ツ 2021-02-14 11:09

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

6条回答
  •  死守一世寂寞
    2021-02-14 11:39

    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.

提交回复
热议问题