连续创建位图会导致内存泄漏

use*_*308 7 c# memory memory-leaks bitmap

我有一个不断生成位图的线程,并截取另一个程序窗口的截图.现在,我的表单上有一个pictureBox,并且不断更新生成的位图.这是我在线程中的代码:

        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);
            }
        }
Run Code Online (Sandbox Code Playgroud)

如您所见,这会导致内存泄漏,因为连续调用新的Bitmap(rect.Width,rect.Height).我已经尝试将"bitmap.Dispose()"添加到while循环的底部,但这导致pictureBox的图像也被处理掉,这使得一个巨大的红色X代替了实际的图像.有没有办法在不丢弃pictureBox图像的情况下处理"位图"?

Luc*_*ero 10

你也在"泄漏"Graphics对象.试试这个:

    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;
        }
    }
Run Code Online (Sandbox Code Playgroud)