【发布时间】: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