在不丢失pictureBox的情况下处理pictureBox图像 [英] Dispose of a pictureBox image without losing the pictureBox

查看:76
本文介绍了在不丢失pictureBox的情况下处理pictureBox图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个将播放幻灯片的程序(除其他外).幻灯片由backgroundWorker控制,并设置为while(true)循环,因此它将不断播放图像.我的问题是我不确定如何处置旧图像,以免它们占用内存(一段时间后程序会引发内存不足异常".如果我调用horPicBox.Image.Dispose(),那么它将之后,我将不再允许我使用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.

是否有一种方法可以从内存中释放旧图像?如果我看一下VS中的诊断工具,则每次图像更改时内存都会增加.

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 ...

注意:ImagePaths是幻灯片图像的文件路径的列表.

Note: ImagePaths is a List of the filepaths for the slideshow images.

这是backgroundWorker运行的代码:

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);
        }
    }

我可以向UI线程报告progressChanged,但是我不确定从UI线程(如果有的话)释放旧图像需要做什么.在此先感谢!

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!!

推荐答案

图像数量和总大小是多少?我认为加载数组中的所有图像并将它们分配给horPicBox比加载它们多次要好.要使用Dispose,首先将horPicBox.Image分配给临时对象,然后将horPicBox.Image分配给null或下一个图像,并在最后为临时对象调用Dispose:

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 horPicBox.Image to 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();

这篇关于在不丢失pictureBox的情况下处理pictureBox图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆