al072
al072

Reputation: 99

Out of Memory exception in Windows Mobile project

Dear programmers, i wrote a program wich target a Windows Mobile platform (NetCF 3.5). My programm has a method of answers check and this method show dynamically created pictureboxes, textboxes and images in new form. Here is a method logic:

 private void ShowAnswer()
{
PictureBox = new PictureBox();
PictureBox.BackColor = Color.Red;
PictureBox.Location = new Point(x,y);
PictureBox.Name = "Name";
PictureBox.Size = Size(w,h);
PictureBox.Image = new Bitmap(\\Image01.jpg);
} 

My problem is in memory leaks or something. If the user work with a programm aproximately 30 minutes and run the ShowAnswer() method several times, Out of memry exception appears. I know that the reason may be in memory allocation of bitmaps, but i even handle the ShowAnswers form closing event and manually trying to release all controls resources and force a garbage collector:

 foreach(Control cntrl in this.Controls)
{
    cntrl.Dispose();
    GC.Collect();
} 

It seems like everything collects and disposes well, every time i check the taskmanager on my windows mobile device during the programm tests and see that memory were released and child form was closed properly, but in every ShowAnswer() method call and close i see a different memory amount in device taskmanager (somtimes it usues 7.5 Mb, sometimes 11.5, sometimes 9.5) any time its different, but it seems like sometimes when the method start to run as usual memory is not allocated and Out of memory exception appears.. Please advice me how to solve my problem.. Maybe i should use another Dispose methods, or i should set bitmap another way.. thank you in advance!!!

Upvotes: 0

Views: 579

Answers (1)

OldTinfoil
OldTinfoil

Reputation: 1215

Depending on how you're handling the form generation, you might need to dispose of the old Image before loading a new one.

private void ShowAnswer()
{
   PictureBox = new PictureBox();
   PictureBox.BackColor = Color.Red;
   PictureBox.Location = new Point(x,y);
   PictureBox.Name = "Name";
   PictureBox.Size = Size(w,h);

   if(PictureBox.Image != null) //depending on how you construct the form
       PictureBox.Image.Dispose();
   PictureBox.Image = new Bitmap(\\Image01.jpg);
}

However, you should also check before you load the image that it's not so obscenely large that it munches up all of your device's memory.

Edit: I don't just mean the size of the compressed image in memory - I also mean the physical size of the image (height & width). The Bitmap will create an uncompressed image that will take up much, much more memory than is resident on storage memory (height*width*4). For a more in-depth explanation, check out the following SO question:

OutOfMemoryException loading big image to Bitmap object with the Compact Framework

Upvotes: 1

Related Questions