[英]Memory Stream using for bitmap image increasing the memory usage
I am using this function which convert thy byte array to image but when this function calls the memory usage of system increasing.This function can be called around 500 times.I tried to dispose or flush to make memory empty but usage still getting increases.I am attaching a task manager image which is showing memory usage. 我正在使用此函数将您的字节数组转换为图像,但是当此函数调用系统的内存使用量增加时,该函数可以被调用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;
}
Don't do this: 不要这样做:
using (var mem = new MemoryStream(imageData))
{
...
mem.Dispose();
}
You are already closing mem
with using
. 您已经
using
关闭mem
。 Also mem.Position
should be 0
by default. 同样,
mem.Position
默认情况下应为0
。 But that's not your problem. 但这不是你的问题。
Try Adding a Background Thread
and check the process memory usage on a while
loop, if it exceeds x
then call GC.Collect()
, so this Disposed elements get deallocated . 尝试添加一个后台
Thread
并在while
循环上检查进程内存使用情况,如果超过x
则调用GC.Collect()
,以便将此Disposed元素释放。 Also after you're done doing whatever with the BitmapImage
set it to null just in case. 同样,在使用
BitmapImage
完成任何操作后,请将其设置为null以防万一。
image.CacheOption = BitmapCacheOption.OnLoad;
Maybe this line has something to do with memory usage, does BitmapCacheOption.Default
make any difference? 也许这行与内存使用有关,
BitmapCacheOption.Default
是否有区别?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.