System.OutOfMemoryException:'内存不足。'

时间:2019-01-03 23:15:10

标签: c# video memory-leaks out-of-memory

更新

我正在使用AForge的videoSourcePlayer。现在我必须为其添加一个功能,因为 GetCurrentVideoFrame( )没有按照我需要的方式工作。因此,我创建了一个名为GetCurrent()的函数,它以我想要的方式工作。我遇到的问题是,当我用它代替GetCurrentVideoFrame( )时遇到了System.OutOfMemoryException:'内存不足。例外,我没有理想。 这是我的代码:

Bitmap getPic2(int i2)
    {
        Bitmap bmp = null;
        Bitmap tempB = null;
        if (endIRList[i2].X > videoSourcePlayer.Width - 1)
            endIRList[i2]= new System.Drawing.Point(videoSourcePlayer.Width - 1, endIRList[i2].Y);
        if (endIRList[i2].Y > videoSourcePlayer.Height - 1)
            endIRList[i2] = new System.Drawing.Point(endIRList[i2].X, videoSourcePlayer.Height - 1);
        if (stIRList[i2].X >= 0 && stIRList[i2].Y >= 0 && endIRList[i2].X < videoSourcePlayer.Width && endIRList[i2].Y < videoSourcePlayer.Height)
        {
            if (endIRList[i2].X - stIRList[i2].X > 0 && endIRList[i2].Y - stIRList[i2].Y > 0)
            {
                bmp = videoSourcePlayer.GetCurrent();
                System.Drawing.Image iOld = p2.Image;
                tempB = bmp.Clone(new Rectangle(stIRList[i2].X, stIRList[i2].Y, endIRList[i2].X - stIRList[i2].X, endIRList[i2].Y - stIRList[i2].Y),bmp.PixelFormat);

                if (iOld != null)
                {
                    iOld.Dispose();
                    iOld = null;
                }
            }
        }
        pictureBox1.Image =this.videoSourcePlayer.GetCurrent();

        TestPicBox.Image = tempB;


        return tempB;
    }

我遇到的问题是:

tempB = bmp.Clone(new Rectangle(stIRList[i2].X, stIRList[i2].Y, endIRList[i2].X - stIRList[i2].X, endIRList[i2].Y - stIRList[i2].Y),bmp.PixelFormat);

现在,如果我只使用bmp = GetCurrentVideoFrame,我不会遇到问题。所以我的函数GetCurrentVideo

一定有问题

这是代码:

  public Bitmap GetCurrentVideoFrame( )
    {
        lock ( sync )
        {
            return ( currentFrame == null ) ? null : AForge.Imaging.Image.Clone( currentFrame );
        }
    }

      public Bitmap GetCurrent()
    {
        lock (sync)
        {
            Bitmap currentPic = null;
            Bitmap original = GetCurrentVideoFrame();
            currentPic = new Bitmap(original, new Size(original.Width / 2, original.Height / 2));
            original.Dispose();
            original = null;
            return currentPic;

        }

    }

我只是看不到它们的功能为什么起作用,而我却看不到。 有人可以帮忙吗?

1 个答案:

答案 0 :(得分:4)

简而言之,您的程序是一种巨大的有效非托管GDI内存泄漏

如果创建或克隆了位图,则需要在某个阶段(使用Dispose方法)将其处置。这个,你没有做

tempB(命名很不正确)和bmp都需要放在某个位置。

您不能希望他们离开或忽略它们。

提示 ,如果您使用位图或不受管理的资源,请特别注意其使用时间和位置,并确保将其丢弃正确