Matteo Montanari Matteo Montanari - 6 days ago 7
Vb.net Question

out of memory exception on new bitmap

in my own application i run an "update" function every 5 seconds, on a timer elapsed event.
This function, fired every 5 sec, updates 45 picturebox images with a variable state "...StatoBrucitore". I can also force this function with a redraw button on the interface; on a stress test, when i clicked this function many times, i have noticed an "out of memory exception".
Here is the code:

Select Case Essiccatoio.RegTemp(Ireg).StatoBruciatore
Case eStato.sOFF
NomeFile = Trim("FlameOff.png")
NomeFile = Percorso & "\Immagini\" & NomeFile
If My.Computer.FileSystem.FileExists(NomeFile) Then
Dim bm As New Bitmap(NomeFile)
PictBruc(Ireg).BackgroundImage = bm
PictBruc(Ireg).Image = Nothing
End If
Case eStato.sAccensione
NomeFile = Trim("FlameTransitorio.gif")
NomeFile = Percorso & "\Immagini\" & NomeFile
If My.Computer.FileSystem.FileExists(NomeFile) Then
Dim bm As New Bitmap(NomeFile)
PictBruc(Ireg).BackgroundImage = Nothing
PictBruc(Ireg).Image = bm
End If
Case eStato.sRegime
NomeFile = Trim("FlameTransitorio.png")
NomeFile = Percorso & "\Immagini\" & NomeFile
If My.Computer.FileSystem.FileExists(NomeFile) Then
Dim bm As New Bitmap(NomeFile)
PictBruc(Ireg).BackgroundImage = bm
PictBruc(Ireg).Image = Nothing
End If
End Select


Note that the in middle case "eStato.sAccensione" is an animated gif, so i can't use a listimage instead of this approach cause i could lost the animation.
I think the problem is the continuous "new Bitmap"...
Anyone has a suggested option to resolve this exception?

Thanks for help

Answer

You are creating a new bitmap with the line:

 Dim bm As New Bitmap(NomeFile)

...but you are not disposing of any previous images. Doing this on a 5 second timer for 45 objects means many new objects per minute. Eventually you wont be able to create any more and get the error.


Since you are assigning one of the same three images, there is no reason to recreate those bitmaps over and over and over. More fundamentally, for 12 picture boxes to show the same image, you dont need 12 different Bitmap objects.

Load the images into an array somewhere at the start of the program:

Private BurnerImgs(2) As Image

' load the array somewhere like form load:
BurnerImgs(0) = Image.FromFile("...")
BurnerImgs(1) = Image.FromFile("...")
BurnerImgs(2) = Image.FromFile("...")

Then assign a given picturebox from there:

PictBruc(Ireg).Image = BurnerImgs(0)

If the images were members of Resources, you'd want to do the same thing. The GetObject() method used to fetch images from resources creates a new image object. So, assigning from resources repeatedly can result in the same issue.

Its a bit easier to load an array from My.Resources though:

Private BurnerImgs As Image()
...
BurnerImgs = New Image() {My.Resources.FlameOn,
                          My.Resources.FlameOff, 
                          My.Resources.WhiteHotFlame}
Comments