哎。 当用户点击这样的项目时,我正在从Isolated Storage中读取图像:
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();
}
}
这样可以正常工作,但如果我在两个图像之间来回点击,内存消耗会不断增加,然后耗尽内存。有没有更有效的方法从隔离存储中读取图像?我可以在内存中缓存一些图像,但是有数百个结果,它最终会占用内存。有什么建议吗?
答案 0 :(得分:2)
您是否在某个时候处置MemoryStream
?这是我能找到的唯一泄漏。
此外,Stream
还有CopyTo()
方法。您的代码可以重写为:
using (IsolatedStorageFile currentIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication())
{
using (var img = currentIsolatedStorage.OpenFile(fileName, FileMode.Open))
{
var imgStream = new MemoryStream(img.Length);
img.CopyTo(imgStream);
return imgStream;
}
}
这将节省许多内存分配。
修改强>
对于Windows Phone(未定义CopyTo()
),将CopyTo()
方法替换为代码:
using (IsolatedStorageFile currentIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication())
{
using (var img = currentIsolatedStorage.OpenFile(fileName, FileMode.Open))
{
var imgStream = new MemoryStream(img.Length);
var buffer = new byte[Math.Min(1024, img.Length)];
int read;
while ((read = img.Read(buffer, 0, buffer.Length)) != 0)
imgStream.Write(buffer, 0, read);
return imgStream;
}
}
这里的主要区别是缓冲区设置得相对较小(1K)。此外,通过为MemoryStream
的构造函数提供图像的长度来添加优化。这使得MemoryStream
预先分配了必要的空间。