How to manage IDisposable Objects that are cached?

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

    An object should be disposed by the class that creates it. Since your callers have not created the items in the cache, they have no business disposing of them, either.

    I'd want to make sure that your factory method is named something like "GetClass" rather than "CreateClass" in order to emphasize that the caller is not responsible for creation, and therefore not for disposal.

提交回复
热议问题