IsolatedStorage causes Memory to run out

筅森魡賤 提交于 2019-12-31 04:36:11

问题


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?


回答1:


Are you disposing the MemoryStream at some point? This is the only leak I could find.

Also, Stream has a CopyTo() method. Your code could be rewritten like:

using (IsolatedStorageFile currentIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication())
{
    using (var img = currentIsolatedStorage.OpenFile(fileName, FileMode.Open))
    {
        var imgStream = new MemoryStream(img.Length);

        img.CopyTo(imgStream);

        return imgStream;
    }
}

This will save many many memory allocations.

EDIT:

And for Windows Phone (which does not define a CopyTo()), replaced the CopyTo() method with it's code:

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;
    }
}

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 makes MemoryStream pre-alloc the necessary space.



来源:https://stackoverflow.com/questions/4127051/isolatedstorage-causes-memory-to-run-out

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!