When should use use dispose? or implement IDisposable versus setting an object to nothing?
what is the most effective way to destroy a created object and free up its used memory?
Printable View
When should use use dispose? or implement IDisposable versus setting an object to nothing?
what is the most effective way to destroy a created object and free up its used memory?
in theory, you don't have to do any of the above. once the Garbage collector goes around, it will detect objects that aren't needed and blow them out. The problem is, you don't WHEN he will come around (just like MY local garbage service).BUT, for some (me included), i like to set the objects to NOTHING at the end of the function.
then whats the point of the dispose method?
u got ME lol :D i've argued that with my co workers too. i still set my objects to nothing regardless. I will look into that cause it IS confusing.
You use dispose when you are using unmanaged objects and need to clean them up manually.
Also it is good to use it when using valuable limited resources and check that they are free before the object is collected. (e.g print queue, database connections, which may be bad for performace if continually needing to wait for a timeout)
If there is no need in your class for these then don't implement IDisposable.
You should also use Dispose on GDI objects like Graphics and Bitmaps, brushes and pens.
Setting your variable to nothing just removes your reference to them, but the image is still in memory.
I have made it a habbit of always disposing an image variable before setting it to a new image, and I can see my memoryusage is reduced quite a bit.
If you only have a few images in your app it probably doesn't matter, but for image-intensive app's it's a must.
VB Code:
'Dispose the image if there allready is an image in memory. 'This has to be done with all bitmap objects to save memory. If Not PictureBox1.Image Is Nothing Then PictureBox1.Image.Dispose PictureBox1.Image=NewImage
With Forms, I use three fixed line of code:
1) Form.close
2) Form.dispose
3) Form=nothing
What I can see is that after disposed , a form is not setted=nothing, I have to do it explicitly. If I well remember (I'm not completely sure), it's true also after a GC.Collect instruction.
Anyway, I've a lot of things to study, yet. Many behaviours of GC are a mistery for me! :rolleyes:
Great question! I wanted to know about it as well for quite sometime. Good thinking guys!