Which graphics objects do I have to dispose?

mcerk

Well-known member
Joined
Nov 1, 2004
Messages
78
Hi. Im drawing with GDI+ a lot in my app. I have a lot of memory leaks. I thought, that this is becouse I do not dispose graphic objects. So, which gr. objects do I need to dispose? Is there a list anywhere?

like:
pen ?, brush?, image?, ...???


tx,

matej
 
As a general rule if it has a Dispose method then call it. Whenever you create an object just check if it has one and if it does then call it when your finished with the object.

Pens, Brushes and Graphics objects are the most common, but there are other.
 
ok, then image object has to be disposed. What about code below.
When I have a function declared as image. Do I have to dispose this function somehow or what???

tx

Code:
the code
dim img as image
img = GetImage(someparameters)
picturebox.image = img
img.dispose

getimage function
Private Function GetImage(someparameters) as Image
   dim img as image
   img = image.fromfile(someparameters)
   GetImage = img
   img.dispose
End Function
 
In that case no you dont want to dispose of the image. Given this code
Code:
the code
dim img as image
img = GetImage(someparameters)
picturebox.image = img
img.dispose

The line img = GetImage(someparameters) creates an image, the following line adds a reference to that image to the picturebox. If you were to dispose of the image you would get a nullreference exception. (I think).
 
You want to dispose of the IDisposable object (in this case an image) when you are finished with it. If the purpose of a function is to return an image, you certainly arent done with the image before you return it. So who disposes of the image?

Some function must call your GetImage function, and that calling function is (generally) the function that will need to dispose of the image. If you put the image in a PictureBox, you will need to hold on to it for a while, in which case, next time you load a different image into the PictureBox, that would be when to call the Dispose method. The key is having some sort of way of knowing when an object is done with and knowing what function is responsible for disposing of it.
 

Similar threads

Back
Top