Dispose Method: .NET provides “Finalize” method in which we can clean up our resources. But relying on this is not always good. This is because it is only called by the GC and you can't determine when it will be called (even though you can force it to be called, but that's not recommended).So the best is to implement “Idisposable” interface and implement the “Dispose” method where you can put your clean up routines.
But benefit of finalize over Dispose is that finalize is executed itself and not required to be called while Dispose is required to be called. So in case we require to execute dispose itself then we can call it within finalize which is executed by CLR while destroying the object. But in case we define call dispose this way also developer called dispose too at somewhere then call dispose can occur twice that can throw exception or some issue so to avoid call twice we can suppress the call to finalize after dispose by using GC.SuppressFinalize within dispose function some in that case if dispose is not called then it will be executed with finalize while if its called then suppressfinalize call will suppress the call to finalize method. Below is the sample code of the pattern. This is the
best way we do clean our unallocated resources and yes not to forget we do not get the hit
of running the Garbage collector twice in this case.
Note:- It will suppress the finalize method thus avoiding the two trip.
Publish Post
Public Class ClsTesting
Implements IDisposable
Public Overloads Sub Dispose()Implements IDisposable.Dispose
' write ytour clean up code here
GC.SuppressFinalize(Me)
End Sub
Protected Overrides Sub Finalize()
Dispose()
End Sub
End Class