问题描述
我有一个创建成本很高的对象,该对象使用一些非托管资源,使用这些资源时必须将其显式释放,并因此实现IDisposable()。我想要一个高速缓存,例如这些昂贵的资源,这样可以最大程度地减少创建成本,但是我在知道如何处理时遇到了麻烦。
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...
推荐答案
一次性对象始终需要有一个明确的所有者,该所有者是负责处理它们。但是,这并不总是创建它们的对象。此外,所有权可以转让。
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<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);
}
编辑:我刚刚注意到该想法在Spring中也存在,在这里被称为。他们的 BorrowObject
和 ReturnObject
方法与我的示例中的方法匹配。
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.
这篇关于如何管理缓存的IDisposable对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!