【问题标题】:Memory Stream using for bitmap image increasing the memory usage用于位图图像的内存流增加了内存使用量
【发布时间】:2017-01-13 03:27:44
【问题描述】:

我正在使用此函数将您的字节数组转换为图像,但是当此函数调用系统的内存使用量增加时。此函数可以调用大约 500 次。我尝试处理或刷新以使内存为空,但使用量仍在增加增加。我附上一个显示内存使用情况的任务管理器图像。

public static BitmapImage ConvertToBitmapImage(byte[] imageData)
    {
        if (imageData == null || imageData.Length == 0) return null;
        var image = new BitmapImage();
        using (var mem = new MemoryStream(imageData))
        {
            mem.Position = 0;
            image.BeginInit();
            image.CreateOptions = BitmapCreateOptions.PreservePixelFormat;
            image.CacheOption = BitmapCacheOption.OnLoad;
            image.UriSource = null;
            image.StreamSource = mem;
            image.EndInit();
            mem.Flush();
            mem.Dispose();
        }
       image.Freeze();
        return image;
    }

Task Manager screen shot

【问题讨论】:

  • 图片丢失。尽管如此。任务管理器不可靠。它显示系统保留的内存量。如果您的应用程序分配了几个大块,Windows 可能会决定为其预分配更多内存。
  • 对不起,我已经编辑了你现在可以看到图像的帖子。应用程序没有分配大块,在这个函数调用获取图像之前大约需要 19mb。
  • 此外,当您分配 new BitmapImage 时,内存使用量也必须增加(因为我看不到您的其余代码,所以我不知道它保留了多长时间,所以我假设您不会立即丢弃它)-我们也没有关于您传入的图像有多大的信息
  • 图像是 100x100 缩略图,在我的应用程序中,我从 web 服务获取字节数组形式的图像,然后使用此函数转换所有图像,每次此函数调用我的类模型的每个实例例如模型有字节数组和位图图像。我在我的应用程序中获得了大约 500 个实例。
  • void getImages(List<Model> models) { foreach(model in models) { model.Image=ConvertToBitmapImage (model.ByteArray); } }

标签: c# wpf


【解决方案1】:

不要这样做:

using (var mem = new MemoryStream(imageData))
{
   ...         
   mem.Dispose();
}

您已经用using 关闭memmem.Position 也应默认为 0。但这不是你的问题。

尝试添加背景Thread 并检查while 循环上的进程内存使用情况,如果它超过x 则调用GC.Collect(),这样Disposed 元素就会被释放。同样,在您完成对 BitmapImage 的任何操作后,请将其设置为 null 以防万一。

image.CacheOption = BitmapCacheOption.OnLoad;

也许这条线与内存使用有关,BitmapCacheOption.Default 有什么不同吗?

【讨论】:

  • 试图注释掉这一行,没有发生变化。
猜你喜欢
  • 1970-01-01
  • 2019-02-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-09-05
  • 1970-01-01
相关资源
最近更新 更多