Dispose() for cleaning up managed resources?

后端 未结 2 1936
庸人自扰
庸人自扰 2020-12-05 00:49

In this answer I found,

Cleanup the unmanaged resources in the Finalize method and the managed ones in the Dispose method, when the Dispose/Finalize

2条回答
  •  旧时难觅i
    2020-12-05 01:08

    If a Foo has resources which will benefit from deterministic cleanup, but none that can be usefully cleaned up in a finalizer, it should implement IDisposable but should not override Finalize or have a destructor. If a class holds multiple resources, and at least one can be cleaned up in a finalizer, then each discrete resource that could be cleaned up in a finalizer should be encapsulated into its own Finalizer/destructor-equipped object (which may be defined in a protected nested class), and the class that would contain those resources should hold references to the wrapper objects. Once that is done, the outer class will fit the pattern for classes with a Dispose method but no finalizer/destructor.

提交回复
热议问题