If .NET has garbage collection then why do you have to explicitly call IDisposable
?
IDisposable. Dispose method. The consumer of an object should call this method when the object is no longer needed. The IDisposable interface is generally provided for the release of unmanaged resources that need to be reclaimed in some order or time dependent manner.
If you access unmanaged resources (e.g. files, database connections etc.) in a class, you should implement IDisposable and overwrite the Dispose method to allow you to control when the memory is freed.
IDisposable is usually used when a class has some expensive or unmanaged resources allocated which need to be released after their usage. Not disposing an object can lead to memory leaks.
By default, the garbage collector automatically calls an object's finalizer before reclaiming its memory. However, if the Dispose method has been called, it is typically unnecessary for the garbage collector to call the disposed object's finalizer.
Garbage collection is for memory. You need to dispose of non-memory resources - file handles, sockets, GDI+ handles, database connections etc. That's typically what underlies an IDisposable
type, although the actual handle can be quite a long way down a chain of references. For example, you might Dispose
an XmlWriter
which disposes a StreamWriter
it has a reference to, which disposes the FileStream
it has a reference to, which releases the file handle itself.
Expanding a bit on other comments:
The Dispose() method should be called on all objects that have references to un-managed resources. Examples of such would include file streams, database connections etc. A basic rule that works most of the time is: "if the .NET object implements IDisposable then you should call Dispose() when you are done with the object.
However, some other things to keep in mind:
Do not implement IDisposable in your own objects unless you absolutely need to. Poorly implemented or unneccessary implementations can actually make things worse instead of better. Some good guidance can be found here:
Implementing a Dispose Method
Or read that whole section of MSDN on Garbage Collection
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With