首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >IsolatedStorage导致内存耗尽

IsolatedStorage导致内存耗尽
EN

Stack Overflow用户
提问于 2010-11-09 03:03:32
回答 1查看 1.2K关注 0票数 1

嘿。当用户单击如下项目时,我正在从独立存储中读取图像:

代码语言:javascript
复制
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();
    }


}

这很好用,但是如果我在两个图像之间来回单击,内存消耗就会不断增加,然后内存就会用完。是否有更有效的方式从独立存储中读取图像?我可以在内存中缓存一些图像,但由于有成百上千的结果,它无论如何都会占用内存。有什么建议吗?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2010-11-09 03:07:06

您会在某个时候处理MemoryStream吗?这是我能找到的唯一的漏洞。

此外,Stream还有一个CopyTo()方法。你的代码可以像这样重写:

代码语言:javascript
复制
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()方法:

代码语言:javascript
复制
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预分配了必要的空间。

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/4127051

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档