使用Image.source时C#WPF内存泄漏

时间:2018-06-30 18:59:19

标签: c# wpf memory memory-management memory-leaks

我要从多台摄像机获取图像,只需将其放在WPF中即可。但是存在内存泄漏问题。这是代码;

        for (int i = 0; i < grabResultsList.Count; i++)
        {


            int width = grabResultsList.ElementAt(i).Width;
            int height = grabResultsList.ElementAt(i).Height;
            byte[] pixels = grabResultsList.ElementAt(i).PixelData as byte[];
            byte[] pixelsnew = getNewByteArray(pixels, width, height);
            int stride = width / 2 * 3;

            BitmapSource bitmap = BitmapSource.Create(width / 2, height / 2, 96d, 96d, pf, null, pixelsnew, stride);

            StackPanel s = MainGrid.Children[i] as StackPanel;
            Image img = s.Children[0] as Image;

            img.Source = bitmap;


            grabResultsList.ElementAt(i).Dispose();
            GC.Collect();
        }

这是从Visual Studio中获取的内存图; CLICK HERE FOR IMAGE

如您所见,RAM图不断增加。

当我评论此行时                 img.Source =位图;

        for (int i = 0; i < grabResultsList.Count; i++)
        {


            int width = grabResultsList.ElementAt(i).Width;
            int height = grabResultsList.ElementAt(i).Height;
            byte[] pixels = grabResultsList.ElementAt(i).PixelData as byte[];
            byte[] pixelsnew = getNewByteArray(pixels, width, height);
            int stride = width / 2 * 3;

            BitmapSource bitmap = BitmapSource.Create(width / 2, height / 2, 96d, 96d, pf, null, pixelsnew, stride);

            StackPanel s = MainGrid.Children[i] as StackPanel;
            Image img = s.Children[0] as Image;

            //img.Source = bitmap;


            grabResultsList.ElementAt(i).Dispose();
            GC.Collect();
        }

CLICK HERE FOR IMAGE

如您所见,RAM图形是恒定的。

我正在使用GarbageCollector,但仍然有此问题。 有什么方法可以处置Image对象或该怎么办?

1 个答案:

答案 0 :(得分:1)

您应先将BitmapSource冻结,然后再将其分配给Image的Source属性:

bitmap.Freeze();
img.Source = bitmap;

除此之外,可以在每个帧上重用WriteableBitmap,而不是在每个帧上创建新的BitmapSource:

var pw = width / 2;
var ph = height / 2;
var bitmap = img.Source as WriteableBitmap;

if (bitmap == null || bitmap.PixelWidth != pw || bitmap.PixelHeight != ph)
{
    bitmap = new WriteableBitmap(pw, ph, 96, 96, pf, null);
    img.Source = bitmap;
}

bitmap.WritePixels(new Int32Rect(0, 0, pw, ph), pixelsnew, stride, 0);