1

我正在制作一个简单的 Windows Phone 8.1 Silverlight 应用程序。这个想法是,我可以用一张照片(用相机拍摄)进行输入,并为其添加标题和描述文本。保存条目后,主页上会出现一个按钮以查看它。所以我做了 3 个条目,它们列在主页上,但是在导航到他们的页面几次后,我得到了 NavigationFailed 和 OutOfMemoryException。页面很简单,它们只包含一张图片和一些文本块。

我认为问题在于图像仍在内存中,这就是为什么我尝试将它们设置为 null 并强制垃圾收集器,但这根本没有帮助。什么可能导致 OutOfMemory 异常?

    protected override void OnNavigatedTo(NavigationEventArgs e)
    {
        base.OnNavigatedTo(e);

        string id= "";
        if (NavigationContext.QueryString.TryGetValue("id", out id))
        {
            foreach (cEntry entry in helper.entries)
            { 
                if (entry.id.ToString() == id)
                {
                    textBlock_viewText.Text = entry.text;
                    textBlock_viewTitle.Text = entry.title;

                    using (IsolatedStorageFile userStore = IsolatedStorageFile.GetUserStoreForApplication())
                    {
                        if (userStore.FileExists(entry.imageFileName))
                        {
                            using (IsolatedStorageFileStream imgStream = userStore.OpenFile(entry.imageFileName, System.IO.FileMode.Open, System.IO.FileAccess.Read))
                            {
                                BitmapImage bmp = new BitmapImage();
                                bmp.SetSource(imgStream);
                                image_viewEntryImage.Source = bmp;
                                bmp = null;
                            }
                        }
                    }
                }
            }
        }
    }

    protected override void OnNavigatedFrom(NavigationEventArgs e)
    {
        base.OnNavigatedFrom(e);
        image_viewEntryImage.Source = null;
        GC.Collect();
    }
4

2 回答 2

0

您可能需要冻结 BitmapImage。

如此处所述,WPF(Windows Phone 开发的典型框架)存在问题,其中 BitmapImages 可能被错误地保持活动状态。虽然它应该在不久前得到修复,但人们报告说在某些情况下仍然看到这个问题。

于 2015-06-01T17:12:32.083 回答
0

不要将 bmp 设置为 null 试试这个。

 public static void DisposeImage(BitmapImage image)
{
    Uri uri= new Uri("oneXone.png", UriKind.Relative);
    StreamResourceInfo sr=Application.GetResourceStream(uri);
    try
    {
        using (Stream stream=sr.Stream)
        {
            image.DecodePixelWidth=1; //This is essential!
            image.SetSource(stream);
        }
    }
    catch { }
}

调用此方法并将源设置为此自定义方法,然后将 bmp 设置为空。GC 无法清除内存。详细信息在这里为什么我的 ListBox 中有图像时会出现 OutOfMemoryException?

于 2015-06-02T06:14:06.663 回答