定期调用 WriteableBitmap.Create() 导致内存泄漏

Periodically calling WriteableBitmap.Create() causing memory leak

我定期从类似相机的设备接收数据(如 sbyte[]、1000 * 1000 像素、RGB),我想在 WPF 应用程序中显示这些数据。因此,我每次(大约 5 FPS)使用静态 class 从数据中创建一个 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) ;
    }
}

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

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

如何修复此内存泄漏?

与其每次都通过 BitmapSource.Create 创建新的 BitmapSource,不如重复使用单个 WriteableBitmap:

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;
    }
}