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?
Are you disposing the
MemoryStreamat some point? This is the only leak I could find.Also,
Streamhas 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
MemoryStreamwith the length of the image. That makesMemoryStreampre-alloc the necessary space.