0

Purpose of my WinForm application is to load and display for a short while randomly selected picture from specific folder. I'm doing this using a PictureBox like so (this line gets adjusted by random number generator to generate different number file name):

 pictureBox1.Image = Image.FromFile(@"C:\pics\1.png");

After a while it loads different image file, but looking at the Diagnostic View, I see that the Process Memory is rising by approx. 1MB with every image loaded. After about 100 pictures, the size rises by 100MB, even though the pictures were replaced. One of the timers that controls display duration includes some methods I found here to try and flush the image from resources:

private void displayDuration(object sender, EventArgs e)
 {
  pictureBox1.Visible = false;
  pictureBox1.Image = null;
  pictureBox1.Invalidate();
  timer2.Enabled = false;
 }

but to no avail. Memory keeps increasing, but the Tick function works since setting visibility to false works just fine.

How do I properly flush this image from memory once I don't need it anymore?

I'm trying not to include ImageList, but if you think it could resolve this memory issue, I could add it in.

Vojmor
  • 1
  • 2
  • You need to dispose the image. – Reza Aghaei May 18 '18 at 03:52
  • Oh I forgot to mention that, I did try the pictureBox1.Dispose() or something like that, but it just ruined the pictureBox for future use and the memory usage kept increasing even though no pictures were displayed, so it had the opposite effect pretty much. But if you're sure that's it, I'll try to fool around with it some more. – Vojmor May 18 '18 at 15:27

1 Answers1

0

Mr. Reza Aghaei was correct, Dispose() does the trick, I just used it wrong:

pictureBox1.Dispose();

which just ruined the pictureBox. Disposing the image in pictureBox is the correct way:

pictureBox1.Image.Dispose();

I shouldn't have given up on that method so early. Thank you very much.

Vojmor
  • 1
  • 2