循环进行Bitmap转BitmapSource导致内存溢出时可使用使用DeleteObject来释放资源

  曾经在一个实时音视频通话的项目中遇到了内存泄漏问题,导致程序运行一段时间后内存溢出,经过分析代码找到了这个罪魁祸首:Bitmap转BitmapSource未释放内存。

原代码如下:

     //显示视频互联画面
        void ShowVideoFrame(VideoFrame frame)
        {
            try
            {
                Stream stream = frame.GetBmpStream();
                Bitmap img = new Bitmap(stream);
                BitmapSource bs = Imaging.CreateBitmapSourceFromHBitmap(img.GetHbitmap(), IntPtr.Zero, Int32Rect.Empty, BitmapSizeOptions.FromEmptyOptions());
                peerPicBox.SetImageSource(bs);
                stream.Dispose();
            }
            catch
            {
            }
        }    

这样每循环一次内存增加 1M-2M左右,长时间的视频通话之后画面无法加载,一直处于黑屏状态。

修改之后的代码:

        [System.Runtime.InteropServices.DllImport("gdi32.dll", SetLastError = true)]
        private static extern bool DeleteObject(IntPtr hObject);
     //显示视频互联画面
        void ShowVideoFrame(VideoFrame frame)
        {
            try
            {
                Stream stream = frame.GetBmpStream();
                Bitmap img = new Bitmap(stream);
                var ptr = bmp.GetHbitmap();
                BitmapSource bs = Imaging.CreateBitmapSourceFromHBitmap(ptr, IntPtr.Zero, Int32Rect.Empty, BitmapSizeOptions.FromEmptyOptions());
                DeleteObject(ptr);//通过删除Bitmap的句柄来释放资源
                peerPicBox.SetImageSource(bs);
                stream.Dispose();
            }
            catch
            {
            }
        }

修改之后程序正常运行。

猜你喜欢

转载自www.cnblogs.com/JungWoo/p/9546220.html