隔离存储导致内存耗尽
嘿。 当用户单击这样的项目时,我正在从独立存储中读取图像:
using (IsolatedStorageFile currentIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication())
{
using (var img = currentIsolatedStorage.OpenFile(fileName, FileMode.Open))
{
byte[] buffer = new byte[img.Length];
imgStream = new MemoryStream(buffer);
//read the imagestream into the byte array
int read;
while ((read = img.Read(buffer, 0, buffer.Length)) > 0)
{
img.Write(buffer, 0, read);
}
img.Close();
}
}
这工作正常,但如果我在两个图像之间来回单击,内存消耗会不断增加,然后耗尽内存。有没有更有效的方法从独立存储中读取图像?我可以在内存中缓存一些图像,但如果有数百个结果,它最终会占用内存。有什么建议吗?
hey.
I'm reading an image from Isolated Storage when the user clicks on an item like this:
using (IsolatedStorageFile currentIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication())
{
using (var img = currentIsolatedStorage.OpenFile(fileName, FileMode.Open))
{
byte[] buffer = new byte[img.Length];
imgStream = new MemoryStream(buffer);
//read the imagestream into the byte array
int read;
while ((read = img.Read(buffer, 0, buffer.Length)) > 0)
{
img.Write(buffer, 0, read);
}
img.Close();
}
}
This works fine, but if I click back and forth between two images, the memory consumption keeps increasing and then runs out of memory. Is there a more efficient way of reading images from Isolated Storage? I could cache a few images in memory, but with hundreds of results, it ends up taking up memory anyway. Any suggestions?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您是否在某个时候处置
MemoryStream
?这是我能找到的唯一泄漏。此外,
Stream
有一个CopyTo()
方法。您的代码可以重写为:这将节省很多内存分配。
编辑:
对于 Windows Phone(未定义
CopyTo()
),用其代码替换CopyTo()
方法:这里的区别是缓冲区设置得比较小(1K)。此外,还通过向
MemoryStream
的构造函数提供图像的长度来添加优化。这使得 MemoryStream 预先分配必要的空间。Are you disposing the
MemoryStream
at some point? This is the only leak I could find.Also,
Stream
has aCopyTo()
method. Your code could be rewritten like:This will save many many memory allocations.
EDIT:
And for Windows Phone (which does not define a
CopyTo()
), replaced theCopyTo()
method with it's code:The main difference here is that the buffer is set relatively small (1K). Also, added an optimization by providing the constructor of
MemoryStream
with the length of the image. That makesMemoryStream
pre-alloc the necessary space.