连续创建位图会导致内存泄漏 [英] Continuous creation of bitmaps leads to memory leak

查看:139
本文介绍了连续创建位图会导致内存泄漏的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个不断生成位图和另需程序的窗口截图线程。现在,我有我的窗体上的图片框,而这不断生成与位图更新。这里的code我在螺纹:

I have a thread that continuously generates bitmaps and takes a screenshot of another program's window. Now, I have a pictureBox on my form, and that's constantly being updated with the bitmaps generated. Here's the code I have in the thread:

        Bitmap bitmap = null;

        while (true)
        {
            if (listBoxIndex != -1)
            {
                Rectangle rect = windowRects[listBoxIndex];
                bitmap = new Bitmap(rect.Width, rect.Height);
                Graphics g = Graphics.FromImage(bitmap);
                IntPtr hdc = g.GetHdc();
                PrintWindow(windows[listBoxIndex], hdc, 0);
                pictureBox1.Image = bitmap;
                g.ReleaseHdc(hdc);
            }
        }

正如你所看到的,这将导致内存泄漏,因为连续调用新的位图(rect.Width,rect.Height)的。我试着加入bitmap.Dispose()到while循环的底部,但导致图片框的形象也被布置,使一个巨大的红色的X来代替实际的形象。有什么办法没有PictureBox的Image处置我可以处理位图的?

As you can see, this leads to a memory leak, because of the continuous call to new Bitmap(rect.Width, rect.Height). I've tried adding "bitmap.Dispose()" to the bottom of the while loop, but that leads to the pictureBox's image also being disposed, which makes a giant red X in place of the actual image. Is there any way I can dispose of "bitmap" without disposing of the pictureBox image?

推荐答案

你也泄露Graphics对象。试试这个:

You're also "leaking" the Graphics object. Try this:

    while (true)
    {
        if (listBoxIndex != -1)
        {
            Rectangle rect = windowRects[listBoxIndex];
            Bitmap bitmap = new Bitmap(rect.Width, rect.Height);
            using (Graphics g = Graphics.FromImage(bitmap))
            {
                IntPtr hdc = g.GetHdc();
                try
                {
                    PrintWindow(windows[listBoxIndex], hdc, 0);
                }
                finally
                {
                    g.ReleaseHdc(hdc);
                }
            }
            if (pictureBox1.Image != null)
            {
                pictureBox1.Image.Dispose();
            }
            pictureBox1.Image = bitmap;
        }
    }

这篇关于连续创建位图会导致内存泄漏的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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