【问题标题】:Periodically calling WriteableBitmap.Create() causing memory leak定期调用 WriteableBitmap.Create() 导致内存泄漏
【发布时间】:2015-10-18 18:58:39
【问题描述】:

我定期从类似相机的设备接收数据(如sbyte[],1000 * 1000px,RGB),我想在 WPF 应用程序中显示这些数据。因此,我每次使用静态类(大约 5 FPS)从数据中创建一个BitmapSource。现在看起来垃圾收集器不再处理我不再需要的数据,所以我的应用程序使用越来越多的内存。我想我将内存韭菜归结为以下部分:

void getImageTimer_Tick(object sender, EventArgs e)
{
    if (_sensor == null) return;
    if (!IsImageGenerationEnabled) return;
    if (!_sensor.UpdateAllFrames()) return;

    ColorImage = ImageSourceGenerator.FromRawByte(_sensor.RawData, _sensor.Width, _sensor.Height);
}

public static class ImageSourceGenerator
{      
    public static ImageSource FromRawByte(sbyte[] colorData, int width, int height)
    {
        if (colorData == null) return null;
        return WriteableBitmap.Create(width, height, 96, 96, PixelFormats.Bgr24, null, colorData, width * 3) ;
    }
}

到目前为止我为缩小问题范围所做的尝试:

  • 已将_sensor.UpdateAllFrames() 注释掉,以确保不是_sensor 导致泄漏。 -> 还在漏水
  • 评论ImageSourceGenerator.FromRawByte() out -> 不泄漏
  • 将静态假数据输入ImageSourceGenerator.FromRawByte() -> 仍在泄漏
  • 总是在ImageSourceGenerator.FromRawByte() 返回null -> 不泄漏
  • 减慢 FPS,也会减慢泄漏速度

到目前为止我为消除泄漏所做的尝试(广告没有修复它):

  • 没有 ImageSourceGenerator 静态并将其包装到 using()-Block 中
  • 在计时器中调用GC.Collect()

如何解决此内存泄漏问题?

【问题讨论】:

  • 为什么不重用单个 WriteableBitmap 并调用 WritePixels 而不是 Create?
  • 嗯。嗯,这很容易——我只是没想到。如果您想在答案中发表评论,我会接受。

标签: c# wpf memory-leaks bitmap


【解决方案1】:

您应该重复使用单个 WriteableBitmap,而不是每次都由 BitmapSource.Create 创建一个新的 BitmapSource:

public static class ImageSourceGenerator
{
    private static WriteableBitmap bitmap;

    public static ImageSource FromRawByte(sbyte[] colorData, int width, int height)
    {
        if (colorData == null)
        {
            return null;
        }

        if (bitmap == null || bitmap.PixelWidth != width || bitmap.PixelHeight != height)
        {
            bitmap = new WriteableBitmap(width, height, 96, 96, PixelFormats.Bgr24, null);
        }

        bitmap.WritePixels(new Int32Rect(0, 0, width, height), colorData, width * 3, 0);

        return bitmap;
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-01-13
    • 1970-01-01
    • 2015-07-06
    • 2014-06-07
    • 2013-11-20
    • 2011-10-28
    • 2016-01-18
    相关资源
    最近更新 更多