如何管理缓存的IDisposable对象?

Sam*_*der 10 .net caching idisposable

我有一个创建成本昂贵的对象,它使用一些必须在完成时显式释放的非托管资源,因此实现IDisposable().我想要一个缓存,例如这些昂贵的资源,以便最大限度地降低创建成本,但我很难知道如何处理这些处理.

如果使用这些对象的方法负责处理,那么我最终会在缓存中放置已处理的实例,然后必须重新创建实例,从而破坏缓存的重点.如果我没有在使用它们的方法中处理对象,那么它们永远不会被处理掉.我认为当它们从缓存中取出时我可以处理它们,但是我可能最终会处理一个仍被方法使用的实例.

让它们超出范围并由垃圾收集器收集并在那时释放资源是否有效?这感觉不对,并反对他们是一次性的想法......

Wim*_*nen 4

一次性物品总是需要有一个明确的所有者来负责处置它们。然而,这并不总是创建它们的对象。此外,所有权可以转让。

认识到这一点,解决方案就变得显而易见了。不要丢弃,回收!您不仅需要一种从缓存获取资源的方法,还需要一种返回资源的方法。此时,缓存再次成为所有者,并且可以选择保留资源以供将来使用或处置它。

   public interface IDisposableItemCache<T> : IDisposable
      where T:IDisposable 
   {
      /// <summary>
      /// Creates a new item, or fetches an available item from the cache.
      /// </summary>
      /// <remarks>
      /// 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
      /// <see cref="Recycle"/>.
      /// </remarks>
      T AcquireItem();

      /// <summary>
      /// Transfers ownership of the item back to the cache.
      /// </summary>
      void Recycle(T item);

   }
Run Code Online (Sandbox Code Playgroud)

编辑:我刚刚注意到这个想法也存在于Spring中,它被称为对象池。它们的BorrowObjectReturnObject方法与我的示例中的方法匹配。