1

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

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


}

这很好用,但是如果我在两个图像之间来回单击,内存消耗会不断增加,然后内存不足。有没有更有效的方式从独立存储中读取图像?我可以在内存中缓存几张图片,但有数百个结果,最终还是会占用内存。有什么建议么?

4

1 回答 1

2

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

还有,StreamCopyTo()方法。您的代码可以重写为:

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(它没有定义 a CopyTo()),CopyTo()用它的代码替换了方法:

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图像长度来添加优化。这使得MemoryStreampre-alloc 成为必要的空间。

于 2010-11-08T19:07:06.227 回答