PictureBox内存释放问题

PictureBox内存释放问题

本文介绍了C#PictureBox内存释放问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是C#的新人.我必须在工作线程中反复刷新GUI图片框.该图像是从使用GetImage方法轮询驱动程序的摄像头获取的,该方法检索要显示的图像.即使我使用指令"using"分配位图并显式调用G.C,内存似乎也从未被释放.

I'm a newby in C#. I have to repeatedly refresh a GUI picture box in a worker thread. The image is acquired from a camera polling a driver with a GetImage method that retrives the image to be displayed. Even if I allocate the bitmap using directive "using" and explicitly call G.C, memory seems to be never deallocated.

工作线程是这样的:

   while (true)
    {
        // request image with IR signal values (array of UInt16)
        image = axLVCam.GetImage(0);
        lut = axLVCam.GetLUT(1);
        DrawPicture(image, lut);
        //GC.Collect();

    }

虽然DrawPicture方法类似

While the DrawPicture method is something like

   public void DrawPicture(object image, object lut)
{

  [...]

    // We have an image - cast it to proper type
    System.UInt16[,] im = image as System.UInt16[,];
    float[] lutTempConversion = lut as float[];

    int lngWidthIrImage = im.GetLength(0);
    int lngHeightIrImage = im.GetLength(1);

    using (Bitmap bmp = new Bitmap(lngWidthIrImage, lngHeightIrImage)) {

      [...many operation on bitmap pixel...]

        // Bitmap is ready - update image control

        //SetControlPropertyThreadSafe(tempTxtBox, "Text", string.Format("{0:0.#}", lutTempConversion[im[160, 100]]));

        //tempTxtBox.Text = string.Format("{0:00000}", im[160, 100]);
        //System.Drawing.Image.FromHbitmap(bmp.GetHbitmap());
        pic.Image = System.Drawing.Image.FromHbitmap(bmp.GetHbitmap());
    }
}

问题出现在

事实上,在注释该行代码时,垃圾回收可以正常工作.更好,问题似乎出在

In fact commenting that line of code, garbage collection works as it would.Better, the problem seems to be with

是否有解决此内存泄漏的建议?

Any advice to solve this memory leak?

非常感谢!

推荐答案

Image实现IDisposable,因此当不再需要创建的每个Image实例时,应在每个Image实例上调用Dispose.您可以尝试在代码中替换此行:

Image implements IDisposable, so you should call Dispose on each Image instance that you create, when it is no longer needed. You could try to replace this line in your code:

pic.Image = System.Drawing.Image.FromHbitmap(bmp.GetHbitmap());

与此:

if (pic.Image != null)
{
    pic.Image.Dispose();
}
pic.Image = System.Drawing.Image.FromHbitmap(bmp.GetHbitmap());

这将在分配新的图像之前处理上一个图像(如果有的话).

This will dispose the previous image (if any) before the new one is assigned.

这篇关于C#PictureBox内存释放问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-16 03:06