Arunava Bhattacharjee
What is the difference between Dispose() and GC.SubpressFinalizer()?
By Arunava Bhattacharjee in .NET on Sep 24 2014
  • Munesh Sharma
    Oct, 2014 1

    GC is garbage collection. It is the automatic memory management, that handles cleanup of objects allocated on the managed heap. The .NET GC employs a mark and sweep algorithm. When a garbage collection occurs it basically considers all object in the part of the heap to be cleaned as recoverable. Then it goes through a marking process where it scans for roots. I.e. it identifies objects that are still in use by the application. Having done that the remaining objects are eligible for cleanup. The heap may be compacted as part of the cleanup.Dispose and finalizer methods both offer an option for cleaning resources, that are not handled by GC. E.g. this could be native handles and the like. They have nothing to do with reclaiming memory on the managed heap.Dispose must be called explicitly on a type which implement IDisposable. It can be called either through the Dispose() method itself or via the using construct. The GC will not call Dispose automatically.A finalizer or destructor (as the language specification calls it) on the other hand will automatically be called sometime after the object was eligible for cleanup. Finalize methods are executed sequentially on a dedicated thread.Dispose() allows deterministic cleanup of resources while a finalizer can act as a safety net in case the user doesn't call Dispose().If a type implements a finalizer, cleanup of instances is delayed as the finalizer must be called prior to cleanup. I.e. it will require an additional collect to reclaim the memory for instances of the type. If the type implements IDisposable as well, the Dispose method can be called and then the instance can remove itself from finalization. This will allow the object to be cleaned up as if it didn't have a finalizer.

    • 0


Most Popular Job Functions


MOST LIKED QUESTIONS