I am writing a program that will play a slideshow (among other things). The slideshow is controlled by a backgroundWorker, and is set to a while(true) loop so it will constantly play images. My problem is I'm not sure how to dispose of the old images so they don't take up memory (after a while the program throws an "Out of memory exception). If I call horPicBox.Image.Dispose() then it won't let me use the pictureBox at all after that.
Is there a way to release the old image from memory?? If I look at the diagnostic tools in VS, the memory goes up each time the image changes ...
Note: ImagePaths is a List of the filepaths for the slideshow images.
This is the code the backgroundWorker runs:
private void PlayImages()
Random r = new Random();
Stopwatch watch = new Stopwatch();
index = r.Next(imagePaths.Count);
horPicBox.Image = Image.FromFile(imagePaths[index]);
while (watch.ElapsedMilliseconds < 5000)
What is the number of images and total size? I think it is better to load all images in array and assign them to
horPicBox than loading them multiple times. To use
Dispose first assign
horPicBox.Image to temp object, then assign
null or next image and call
Dispose at the end for the temp object:
Image img = horPicBox.Image; horPicBox.Image = Image.FromFile(imagePaths[index]); if ( img != null ) img.Dispose();