IsolatedStorage causes Memory to run out

大城市里の小女人 提交于 2019-12-02 06:52:40

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.

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