How to manage IDisposable Objects that are cached?

前端 未结 6 2102
囚心锁ツ
囚心锁ツ 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条回答
  •  -上瘾入骨i
    2021-02-14 11:49

    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
          // 
        }
      }
    }
    

提交回复
热议问题