Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
351 views
in Technique[技术] by (71.8m points)

c# - Dispose of a pictureBox image without losing the pictureBox

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 ... enter image description here

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();
        int index;
        Stopwatch watch = new Stopwatch();

        while (true)
        {
            index = r.Next(imagePaths.Count);
            horPicBox.Image = Image.FromFile(imagePaths[index]);

            watch.Start();

            while (watch.ElapsedMilliseconds < 5000)
            {

            }

            watch.Stop();
            watch.Reset();

            //picWorker.ReportProgress(0);
        }
    }

I can report progressChanged to the UI thread, but I'm not sure what I need to do from the UI thread (if anything) to release the old Image(s). Thanks in advance!!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

What if you store the image to variable of that type and then set your picturebox image and then dispose the older one like

       Image oldImage = horPicBox.Image;
       horPicBox.Image = Image.FromFile(imagePaths[index]);
       oldImage.Dispose();

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...