How to manage IDisposable Objects that are cached?

前端 未结 6 2097
囚心锁ツ
囚心锁ツ 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:44

    You could decouple the unmanaged resources from the managed instance and use a cache manager to hold a set of unmanaged resources. The managed object will try to acquire an instance of the unmanaged resource from the cache manager which will either create one or give one free instance from the cache and return it to the cache manager (instead of disposing it itself) at the time of its disposal. The cache manager will be the sole responsible object for allocating and freeing unmanaged resources when it sees it's necessary.

提交回复
热议问题