简体   繁体   中英

Memory Leak changing images in Windows Phone 7

I have a problem when I change multiple times the image of an Image Container in the Windows Phone 7.5

Here's the faulty code:

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<double> e)
{
    // do something
    if (this.slider1 != null)
    {
        currentSlice = (int) this.slider1.Value;
        displayImages();
    }
}

After some changes (approximately 100 I ran out of memory)

I have already tried setting the image.Source to null before assigning a new value.

The default behaviour of the Image control is to cache the image for future reuse. This means that the memory is still used by the contorl. You need to explicitly release the references to the image to free the memory

Like this:

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

See more at: http://blogs.msdn.com/b/swick/archive/2011/04/07/image-tips-for-windows-phone-7.aspx

It is hard to pinpoint from the code snippets in the post the cause of the memory leak. One suggestion is to look for short lived objects subscribing events on objects with longer lifetimes. You should profile your application to see what's going on in managed memory like objects surviving, etc. Check out Memory Profiling for Application Performance blogpost to see how you can use the profiler to detect memory issues.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM