6

I have a list "images" that contains about 20 photos about 1MB each. I want to scroll through the images in the list by clicking the next button. But after about 8 pictures I get out of memory.

    private void button4_Click(object sender, EventArgs e) //next
    {
        index++;
        if (index >= images.Count) index = 0;
        CurrImage = images[index]; 
        Bitmap b = new Bitmap((Bitmap)CurrImage.Clone()); //breakpoint occurs her
        pictureBox1.Image = b; 

        NewThread = new Thread(new ThreadStart(ChooseColors2));
    }

ChooseColors2 thread will use "CurrImage" so to avoid race conditions, I avoided that by creating a new bitmap as shown above

Please note that if I use pictureBox1.Image = CurrImage; without creating a new bit map I don't get this error but there will be race condition exception with the thread.

Dale K
  • 25,246
  • 15
  • 42
  • 71
Basco
  • 87
  • 1
  • 1
  • 7

2 Answers2

4

You could try calling the following before assigning a new Bitmap to pictureBox1.Image, to remove the previous "new" Bitmap and free up resources:

pictureBox1.Image.Dispose();
Grant Winney
  • 65,241
  • 13
  • 115
  • 165
  • 3
    Thanks Grant, I think I need to read more about memory leak. When ever I think That I have become a programmer, I then realize that I am still miles away. Thanks anyway for your help. – Basco Mar 19 '13 at 06:01
0

I believe that you can try also to make use of using keyword; as it will make sure that the object is disposed directly after it's scope. you can make it this way:

using (Bitmap b = new Bitmap((Bitmap)CurrImage.Clone()))
{
    pictureBox1.Image = b;
}`

For more details, please have a look at What are the uses of “using” in C#.

Dale K
  • 25,246
  • 15
  • 42
  • 71
M Mabrouk
  • 1
  • 1
  • 2