-2

so i got this program that i built. there's some of the code

        private void button1_Click(object sender, EventArgs e)
    {
        OpenFileDialog openDialog = new OpenFileDialog();
        if (openDialog.ShowDialog() == DialogResult.OK)
        {
            image1 = new Bitmap(openDialog.FileName);
            pictureBox1.Image = image1;
        }
    }

now every time that i change the picture with the button the ram usage is increased. a friend of mine told me that's happened because i'm assign new memory space every time i'm doing this :

new Bitmap(openDialog.Filename);

what's the solution for this? (i tried to search in google but i didnt really know what to search for that..)

EDIT :

now its working thanks for help. edited code for others :

        private void button1_Click(object sender, EventArgs e)
{
    OpenFileDialog openDialog = new OpenFileDialog();
    if (openDialog.ShowDialog() == DialogResult.OK)
    {
     if (pictureBox1.Image != null)
         pictureBox1.Image.Dispose();

        image1 = new Bitmap(openDialog.FileName);
        pictureBox1.Image = image1;
    }
}
ShmuelCohen
  • 472
  • 3
  • 9
  • 17

1 Answers1

1

Note: Always call Dispose before you release your last reference to the Image. Otherwise, the resources it is using will not be freed until the garbage collector calls the Image object's Finalize method.

As the MSDN documentation says, you must call Dispose. If you want to extract something from image and then dispose, it's better to use the Using keyword; e.g.:

using(var bmp = new Bitmap(bitmapLocation)){
    // extract data from bitmap
}

After execution leaves the using braces, the bitmap's Dispose method will be called and the object will be disposed.

Cody Gray - on strike
  • 239,200
  • 50
  • 490
  • 574
Davit Tvildiani
  • 1,915
  • 3
  • 19
  • 29