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
You can solve this with a class factory and IDisposable. For example:
public class CachedObject : IDisposable {
private int mRefCount;
private CachedObject(int something) {
mRefCount = 1;
}
public static CachedObject CreateObject(int something) {
CachedObject obj = LookupInCache(something);
if (obj != null) Interlocked.Increment(ref obj.mRefCount);
else obj = new CachedObject(something);
return obj;
}
private static CachedObject LookupInCache(int something) {
CachedObject obj = null;
// Implement cache lookup here, don't forget to lock
//..
return obj;
}
public void Dispose() {
int cnt = Interlocked.Decrement(ref mRefCount);
if (cnt == 0) {
// Remove from cache
//
}
}
}