如何修复此图像内存泄漏?

时间:2012-02-05 21:14:28

标签: windows-phone-7

更新 手动运行垃圾收集会清除内存,因此本身并不是“泄漏”

我有一个图像查看器页面,我正在传递各种.jpg图像的Web URL。当我使用Windows Phone性能分析工具运行时,每次加载新图像时,我使用的内存都会启动星形图(12个图像会让我达到50MB)。我尝试使用此处显示的方法http://blogs.msdn.com/b/swick/archive/2011/04/07/image-tips-for-windows-phone-7.aspx清除图像缓存,但它似乎不起作用。

图片浏览器:

<!--ContentPanel - place additional content here-->
<Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
    <Image x:Name="ThumbnailImage" Height="275" Margin="0,0,0,12"/>
</Grid>

代码背后:

protected override void OnNavigatedTo(NavigationEventArgs e)
{
    string imageurl;
    if (NavigationContext.QueryString.TryGetValue("imageurl", out imageurl))
    {
        BitmapImage bitmapImage = ThumbnailImage.Source as BitmapImage;

        if ( bitmapImage != null)
            bitmapImage.UriSource = null;

        ThumbnailImage.Source = null;
        ThumbnailImage.Source = new BitmapImage(new Uri(imageurl));
     }
  }

3 个答案:

答案 0 :(得分:2)

系统在认为需要时调用GC。在桌面版.NET上,有两个主要条件:

  • 当第0代对象(自上次垃圾回收以来创建的对象)的数量超过预定义数量
  • 当可用内存变得太低而开始变得危险时

我不知道Windows Phone垃圾收集器的条件是什么,但除非你开始获得OutOfMemory异常,否则你不应该担心内存。

答案 1 :(得分:0)

您继续处理图像并重新初始化。只需执行以下操作:

string imageurl;
if (NavigationContext.QueryString.TryGetValue("imageurl", out imageurl))
    ThumbnailImage.Source = new BitmapImage(new Uri(imageurl));

答案 2 :(得分:0)

我认为问题是由于您不断创建基于GDI +且因此部分未受管理的新BitmapImage对象。这是一个相当常见的问题,可以通过重用相同的BitmapImage对象来纠正。但是,考虑到应用程序的设计,可能更容易在BitmapImage类中使用构建的替代方法。每当我需要对WP7上的图像做任何事情时,我总是使用ImageTools。输出可以直接用于控件中,并且性能更高(并具有预期的GC特性)