views:

142

answers:

3

Following on from my question here http://stackoverflow.com/questions/2548664/long-overdue-for-me-question-about-disposing-managed-objects-in-net-vb-net ,

If I replace an image in a picture box, should I dispose the original image first?

Or, what about this situation:

Dim bm As New Bitmap(32,32)  
bm = New Bitmap(32,32)  
bm = New Bitmap(32,32)  
bm = New Bitmap(32,32)  

Does bm need only to be disposed at the end, or should it be disposed before each re-creation?


Thanks all for the answers. A big oversight there on my part. I knew a control took care of disposing its children but It hadn't occurred to me that I should dispose an old image if I replaced it.

+2  A: 

Yes, you should dispose the old object before you create a new image on top of the same variable. By creating a new image with the same variable, you are removing a reference to it. If there are no references to the old object, you are signifying that it should be picked up by the GC (Garbage Collector). Although technically, this "should" eventually result in the memory being freed assuming that the finalizer makes sure that non-managed resources are taken care of, this is a big assumption (You can't even really assume that the finalizer will be called), and it causes more work for the system. Non-default finalizers causes extra work for the GC in terms of garbage collection level promotion, resulting in taking longer for the memory to be deallocated, and the number of times the GC has to run to do so.

This is assuming that is all written to make sure the finalizer handles it. Anytime an object has a Dispose method (anything which implements IDisposable which BitMap does), it should be called before removing reference to the object (falling out of scope, removing reference to the object etc.).

Here is an article on how the Garbage Collector works in .net

http://www.devx.com/dotnet/Article/33167

Here is how MS says the dispose / finalizer should be implemented:

http://msdn.microsoft.com/en-us/library/b1yfkh5e.aspx

Kevin
+2  A: 

Yes you should. It implements IDisposable.
As general rule of thumb, dispose all objects that implements IDisposable. Do not leave it to GC.

cornerback84
+1  A: 

Does bm need only to be disposed at the end, or should it be disposed before each re-creation?

It should be disposed before each "recreation". Do not confuse an object with an object reference. "new Bitmap" creates a new object. "bm" is a reference that happens to point to that object. They are not the same. You are not "recreating" any object here - you are creating a new object, and then dropping all references to the previous object, meaning that i will be garbage collected some time in the (near) future.

danbystrom
Thanks for clearing that up for me. I'm aware of all the concepts in your answer, but some days I have a brain freeze! Ever forgotten how to spell a short word? That's what it feels like.
Jules