Is this a resource leak?

P

Paul E Collins

Here's some code I'm using:

Image img = new Bitmap(32, 16);
PictureBox pic = new PictureBox();
pic.Image = img;
myForm.Controls.Add(pic);
// ... img now goes out of scope ...

I'm assuming that, when myForm gets closed, then pic is Disposed (as
part of the Controls collection) and at the same time Disposes of the
"new Bitmap" I assigned to its Image property. Is this correct, or do
I need to do something else to avoid a resource leak?

Eq.
 
M

Marina Levit [MVP]

I don't see a resource leak here, looks good to me. When the form is closed,
the object 'pic' is pointing to should be eligible for GC along with the
form, as long as nothing from outside the form is pointing to it. The 'pic'
variable itself goes out of scope as soon as the method this is all in is
done running, but since the picturebox object has been added to the form's
controls collection, the form has a point to it, and the object does not get
GC'ed until the form object is no longer being used by anything.
 
G

Greg Young

Whether or not this is good behavior depends on the internal dispose of the
picturebox (whether it will in turn dispose the bitmap or whether the bitmap
will hang around for finalization). Either way this is not a "leak"

Cheers,

Greg
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top