The garbage collector and the finalizer / destructor are inextricably linked - however, most objects do not need (and do not have) a destructor. In fact, they are very rare in managed code and are commonly used to ensure the release of unmanaged resources. If the object has a destructor / finalizer, the garbage collector calls it at about the same time as the collection (possibly in the next pass). Garbage collection is non-deterministic - this happens when it happens - often due to memory pressure.
However, IDisposable is more common. This allows a more predictable pattern for allocating resources now (rather than when executing a GC). Often classes that have a finalizer will also be IDisposable, while the Dispose () implementation disables the destructor (it is not needed if we have already cleared it). Please note: Dispose () is not related to garbage collection, but has language support through the "using" statement.
IDisposable is much more than finalizers. You are responsible for ensuring that everything that is IDisposable is deleted. Additional note: deleting something does not lead to the collection of the object; this is done only by the GC according to any schedule selected by the GC. Elimination, rather, the release of related resources. For example, you do not want the file to be locked until the GC happens; Dispose () here unlocks the file (releasing the file descriptor of the OS).
Marc gravell
source share