thank you.
difference between dispose and finalize methods in c#?
163624-Jan-2016
I know about finalizer and dispose both are used for same task like to free unmanaged resources but have some differences.I want to know about its differences.Please give me a better solution.
Shiva Shukla
24-Jan-2016Now when garbage collector runs for the first time it searches for objects whose memory has to free. He can see three objects but only cleans the memory for Object1 and Object3. Object2 it pushes to the finalization queue.
Now garbage collector runs for the second time. The garbage collector gets to know there are no objects to be released and then checks for the finalization queue and at this moment, it clears object2 from the memory.
So if you notice that object2 was released from memory in the second round and not first. That is why the best practice is not to write clean up Non .NET resources in Finalize method rather use the DISPOSE.
Dispose method belongs to ‘IDisposable’ interface. We had seen in the previous section how bad it can be to override the finalize method for writing the cleaning of unmanaged resources. So if any object wants to release its unmanaged code best is to implement IDisposable and override the Dispose method of IDisposable interface. Now once your class has exposed the Dispose method it is the responsibility of the client to call the Dispose method to do the cleanup.
Output:-