0

Finalize() -
this function will clean up the Unmanaged resources during Garbage collection process only -
User is unaware when this method is actually executed.
Also the user cannot call this function directly to clean up memory.

Dispose() -
By implementing IDisposable interface ,user can clean up UnManaged Resources,where the user will know exactly when the resources are freed up.

My understanding is that Finalize() cannot be overridden to clean up unmanaged resources.
This is a system process only for 'GC' process will use for cleaning up unmanaged resources.
If user need to clean up resources on their own , then he/she should implement IDisposable interface and call Dispose() explicitly. No other possibility !
And the best practice in Cleaning up unmanaged resources is using 'USING' statement.

Question 1: Is my understanding correct ? Please correct me in my above statements , if i am wrong.

Question 2: Also , i wanted to know ,can I Clean up Managed resources by Implementing IDisposable interface and by a call to Dispose() ?

Stefan Walter
  • 602
  • 3
  • 10
Simbu
  • 41
  • 7
  • 3
    http://stackoverflow.com/questions/732864/finalize-vs-dispose – Roy Dictus Sep 30 '13 at 13:55
  • finally both the methods release unmanaged resources .What is the one thing , that differentiate the usage of Finalize() & Dispose() – Simbu Sep 30 '13 at 14:41
  • Dispose() is the only method that releases unmanaged resources and it is supposed to be called explicitly, when you kill an object. Finalize() is called by the CLR and while it will call Dispose(), relying on Finalize() (and so not calling Dispose() yourself) means you have absolutely no control over when unmanaged resources are released. This may mean that you keep database connections open unnecessarily etc. Therefore: when you have unmanaged resources, implement both IDisposable and Finalize(), and make sure your callers call Dispose(). – Roy Dictus Oct 01 '13 at 09:46
  • Hmm, Object.Finalize() is always overridden. Actually doing this is 99.99% of the time dead wrong. A .NET 1.x detail that seems impossible to get rid of. Finalizable resources should have their own wrapper classes, starting with SafeHandle and friends. – Hans Passant Sep 17 '14 at 15:55

1 Answers1

1

Finalize doesn't clean up memory. It handles unmanaged resources. In a .NET application memory is a managed resource and allocating and freeing memory is handled by the runtime. You don't have to do anything special. The garbage collector will reclaim memory as objects become eligible for collection.

This leads to the answer to your second question: No you cannot use IDisposable to clean up memory, because memory is automatically reclaimed through garbage collection. Use IDisposable to handle resources that are not handled by GC such as handles.

Brian Rasmussen
  • 114,645
  • 34
  • 221
  • 317