How to manage IDisposable Objects that are cached?

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

    First of all, the type that wraps the native resources should be finalizable, not just disposable. Even better, use SafeHandle to wrap the native resources.

    Unless someone is explicitly responsible for saying they are done with the item and it can be disposed, then I think you're better off letting the GC take care of it. Note that it must be finalizable though, otherwise the GC won't give it a second glance.

提交回复
热议问题