How to manage IDisposable Objects that are cached?

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

    To (mis-)quote Raymond Chen: Every cache without an expiration policy is a leak

    So, set a clear cache expiration policy, and let the cache dispose them as the normal case. This still leaves application shutdown to be handled.

    If your unmanaged ressources are owned by the process, you can let the process release them on shutdown.

    If the unmanaged ressources are not owned by the process, you need to detect shutdown and explicitely Dispose the cached elements.

    If you can't detect process shutdown reliably, and the managed ressources are expensive, the unmanaged ones are not, separate the managed from the unmanaged ressources, and let the cache keep only the managed ones.

    When the unmanaged ressources are expensive so they need caching, and they are not owned by the process, and you cannot detect process shutdown reliably and you cannot afford to leak them, then your problem cannot be solved.

提交回复
热议问题