Reputation: 31
Can anyone explain the differences between Dispose,Destructor and Finalise in .Net clearly ?
And when to use them?
Upvotes: 1
Views: 550
Reputation: 81159
If a class implements IDisposable
, then anyone calling that class' constructor should ensure that the resulting instance's IDisposable.Dispose()
method will get called sometime between that instance's last use and its abandonment. Typically, a class will implement IDisposable
if, at some point in its lifetime, an instance will ask some other entity (which could be just about anything, and may not even be on the same computer!) to start doing something on its behalf, which the other entity will do until instructed otherwise. The IDisposable.Dispose()
method will cause the instance to instruct all such entities that they no longer need to do whatever they were doing on the its behalf.
To allow for the possibility that objects might be (wrongfully) abandoned without IDisposable.Dispose()
having been called first, .net and Java allow objects to request notification if the system discovers that they've been abandoned. Such notification takes the form of a call to a method called Finalize
. Note that there is no guarantee as to how much time elapses between an object's abandonment and a call to Finalize()
. In some cases, if one isn't careful, the system may call Finalize
on an object while it's busy using the services of some other object which is acting on its behalf (thereby causing the other object to stop providing its services while they are still needed).
Because the creators of the C# standard didn't like the idea of people writing code that would require a framework to include an overridable Finalize
method in every object, C# compilers don't allow code to override finalize. Instead, out of an apparent misguided belief that abandoned-object can and should be portable, they require one to write a block of code using syntax similar to a C++ destructor. Such a block is called a destructor, though it behaves nothing like a C++ one. Instead, it generates an override for Finalize
along with some other code. Note that any code which properly uses a destructor in .net must use the methods GC.SuppressFinalize()
and GC.KeepAlive()
, so requiring the use of destructor sequence rather than an Object.Finalize()
override does nothing to enhance portability.
Upvotes: 1