Matteo Montanari Matteo Montanari - 4 months ago 36
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

If you are simply assigning one of the same three images to some number of PictureBoxes, there is no reason to recreate those bitmaps over and over and over. More fundamentally, if you want 12 picture boxes to show the same image, you dont need 12 different Bitmaps.

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

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

Then, just 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, but could do so more easily:

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