SiteMap  | About    

Finalize() Vs Dispose() methods

Dispose() is called when we want for an object to release any unmanaged resources with them. On the other hand Finalize() is used for the same purpose but it doesn't assure the garbage collection of an object.

One of the benefits of .NET is the GC (Garbage Collector). It is the automatic memory management , that handles cleanup of objects allocated on the managed heap. The .NET Garbage Collector 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. 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 Garbage Collector. 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 Garbage Collector will not call Dispose automatically.

A finalizer or destructor 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 and you have no guarantee when this will happen (you can force it, but it will hurt performance). Finalizers should always be protected, not public or private so that the method cannot be called from the application's code directly and at the same time, it can make a call to the base.Finalize method

Microsoft recommends that you implement both Dispose and Finalize when working with unmanaged resources. The Finalize implementation would run and the resources would still be released when the object is garbage collected even if a developer neglected to call the Dispose method explicitly. (C) 2017    Founded by raps mk
All Rights Reserved. All other trademarks are property of their respective owners.