IsolatedStorage导致内存用尽 [英] IsolatedStorage causes Memory to run out

查看:75
本文介绍了IsolatedStorage导致内存用尽的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

嘿. 当用户单击这样的项目时,我正在从隔离存储中读取图像:

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?

推荐答案

您是否正在处置MemoryStream?这是我唯一能找到的泄漏.

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

此外,Stream具有CopyTo()方法.您的代码可以按如下方式重写:

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.

对于Windows Phone(未定义CopyTo()),将CopyTo()方法替换为其代码:

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

这里的主要区别是缓冲区设置得相对较小(1K).另外,通过为MemoryStream的构造函数提供图像的长度来添加优化.这使得MemoryStream预分配必要的空间.

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.

这篇关于IsolatedStorage导致内存用尽的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆