内存泄漏更改Windows Phone 7中的图像

当我在Windows Phone 7.5中多次更改图像容器的图像时,我遇到了问题

这是错误的代码:

public void displayImages() { image1.Source = new System.Windows.Media.Imaging.BitmapImage (new Uri("BrainImg/axis/" + axis + currentSlice + ".jpg", UriKind.RelativeOrAbsolute)); image2.Source = new System.Windows.Media.Imaging.BitmapImage (new Uri("BrainImg/aseg/" + axis + currentSlice + ".png", UriKind.RelativeOrAbsolute)); } private void slider1_ValueChanged(object sender, RoutedPropertyChangedEventArgs e) { // do something if (this.slider1 != null) { currentSlice = (int) this.slider1.Value; displayImages(); } } 

经过一些更改(大约100我内存不足)

在分配新值之前,我已经尝试将image.Source设置为null

Image控件的默认行为是缓存图像以供将来重用。 这意味着控制器仍在使用内存。 您需要显式释放对图像的引用以释放内存

像这样:

  BitmapImage bitmapImage = image.Source as BitmapImage; bitmapImage.UriSource = null; image.Source = null; 

有关详细信息,请访问: http : //blogs.msdn.com/b/swick/archive/2011/04/07/image-tips-for-windows-phone-7.aspx

很难从post中的代码片段中查明内存泄漏的原因。 一个建议是寻找在生命周期较长的对象上订阅事件的短期对象。 您应该分析您的应用程序,以查看托管内存中正在发生的事情,例如幸存的对象等。查看应用程序性能的内存分析博客文章,了解如何使用分析器来检测内存问题。