difference between destructor and garbage collector

后端 未结 4 555
执念已碎
执念已碎 2020-12-31 19:18

I want to know is there any difference between destructor and garbage collector, destructor is used to dispose of all unused objects at the end of the lifetime of the applic

4条回答
  •  傲寒
    傲寒 (楼主)
    2020-12-31 19:55

    The garbage collector and finalizer/destructor are intrinsically linked - however, most objects do not need (and do not have) a destructor. They are actually very rare in managed code, and are usually used to ensure unmanaged resources are released. If an object has a destructor/finalizer, the garbage collector invokes it around the same time as collection (maybe in the next pass). Garbage collection is non-deterministic - it happens when it happens - often relating to memory pressure.

    Far more common, however, is IDisposable. This allows a more predictable pattern for releasing resources now (rather than when GC next happens). Often, classes that have a finalizer will also be IDisposable, with the Dispose() implementation disabling the destructor (it isn't needed if we've already cleaned up). Note that Dispose() is unrelated to garbage collection, but has language support via the "using" statement.

    IDisposable is much more common than finalizers. You are responsible for ensuring anything IDisposable gets disposed. Additional note: disposing something does not cause the object to get collected; that is done only by the GC on whatever schedule the GC chooses. Disposal, rather, release associated resources. As an example, you wouldn't want a file being locked open until GC happens; the Dispose() here unlocks the file (by releasing the OS file handle).

提交回复
热议问题