WP7中出现内存不足异常



当我试图将一些图像保存到IsolatedStorage时,会发生内存不足异常。如果图像计数大于20,则会发生此错误。我正在下载所有这些图像,并将它们保存在隔离存储的临时文件夹中。当我试图将这些图像从临时文件夹保存到隔离存储中名为myImages的文件夹时,会发生此错误。每张照片都是从temp中读取并逐一写入myImages。当大约20或25张照片保存到myImages时,就会发生此错误。图像的平均大小为350-400 KB。如何避免此错误?

我的代码是:

private void SaveImages(int imageCount)
{
    IsolatedStorageFile isf = IsolatedStorageFile.GetUserStoreForApplication();
    BitmapImage bitmap;
    string tempfoldername = "Temp";
    string tempfilename = string.Empty;
    string folderName = "myImages";
    string imageName = string.Empty;
    for (int i = 0; i < imageCount; i++)
    {
        tempfilename = tempfoldername + "\" + (i + 1) + ".jpg";
        bitmap = GetImage(tempfoldername, tempfilename);
        imageName = folderName + "\" + (i + 1) + ".jpg";
        SaveImage(bitmap, imageName, folderName);
        if (isf.FileExists(imageName))
            isf.DeleteFile(imageName);
        bitmap = null;
    }
}
private BitmapImage GetImage(string foldername, string imageName)
{
    IsolatedStorageFile isf = IsolatedStorageFile.GetUserStoreForApplication();
    IsolatedStorageFileStream isfs;
    BitmapImage bi = new BitmapImage();
    MemoryStream ms = new MemoryStream();
    byte[] data;
    int FileSize = 0;
    if (isf.DirectoryExists(foldername))
    {
        isfs = isf.OpenFile(imageName, FileMode.Open, FileAccess.Read);
        data = new byte[isfs.Length];
        isfs.Read(data, 0, data.Length);
        ms.Write(data, 0, data.Length);
        FileSize = data.Length;
        isfs.Close();
        isfs.Dispose();
        bi.SetSource(ms);
        ms.Dispose();
        ms.Close();
        return bi;
    }
    return null;
}
private void SaveImage(BitmapImage bitmap, string imageName, string folderName)
{
    int orientation = 0;
    int quality = 100;
    using (IsolatedStorageFile isf = IsolatedStorageFile.GetUserStoreForApplication())
    {
        if (!isf.DirectoryExists(folderName))
            isf.CreateDirectory(folderName);
        if (isf.FileExists(imageName))
            isf.DeleteFile(imageName);
        Stream fileStream = isf.CreateFile(imageName);
        WriteableBitmap wb = new WriteableBitmap(bi);
        wb.SaveJpeg(fileStream, wb.PixelWidth, wb.PixelHeight, orientation, quality);
        fileStream.Close();
    }
}

如何修复此错误?

您的BitmapImage很可能会泄漏内存
请确保将UriSource设置为null,以便释放内存。

看看http://blogs.msdn.com/b/swick/archive/2011/04/07/image-tips-for-windows-phone-7.aspx了解更多信息。

最新更新