Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

If I replace an image in a PictureBox control, should I dispose the original image first?

Following on from my question here, 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.

like image 392
Jules Avatar asked Apr 10 '10 12:04

Jules


People also ask

What is the function of the SizeMode property of the PictureBox control?

The SizeMode property, which is set to values in the PictureBoxSizeMode enumeration, controls the clipping and positioning of the image in the display area. You can change the size of the display area at run time with the ClientSize property. By default, the PictureBox control is displayed by without any borders.


1 Answers

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

like image 161
kemiller2002 Avatar answered Sep 20 '22 23:09

kemiller2002