0

I saw tons of threads with memory leaking while using images. So, is it a good idea just to have a general function, some kind of own GC, which would run at NavigatingFrom, find all images (even in templates of virtualized lists) and set them to null?

Vitalii Vasylenko
  • 4,776
  • 5
  • 40
  • 64

1 Answers1

2

Here is an helper to iterate throught all the images of your page:

public IEnumerable<Image> GetAllImage(DependencyObject root)
    {
        var count = VisualTreeHelper.GetChildrenCount(parentElement);


        for (int i = 0; i < count; i++)
        {
            var child = VisualTreeHelper.GetChild(parentElement, i);
            if (child is Image)
            {
                yield return (Image)child;
            }
            foreach (var image in GetAllImage(child))
            {
                yield return image;
            }

        }
    }

You can just call it with the root of your page as parameter and it should return all the images to you.

Benoit Catherinet
  • 3,335
  • 1
  • 13
  • 12
  • Sounds good. So, if i'd call it for the listbox, it should return all items images? Thanks, i'll try it. – Vitalii Vasylenko Sep 19 '13 at 17:13
  • Just keep in mind that if you really have a page leak this will just fix the more important part of the leak (because it's what is taking the most space) but not the actual leak itself – Benoit Catherinet Sep 19 '13 at 17:17
  • Hm.. why? Afaik, problem is about auto-caching images data. Setting images to null would release them, isnt it? – Vitalii Vasylenko Sep 19 '13 at 17:20
  • yes setting it like this (http://stackoverflow.com/questions/7062820/clear-cache-in-window-phone-7) should release the image from the cache but I'm suspecting the reason they are kept in cache is because you have a memory leak for another reason – Benoit Catherinet Sep 19 '13 at 17:33
  • Yep, that's what i want to apply to all images in listbox. But what can be a reason then? I'm loading page with listbox, in WM's OnNavigatedTo(), i'm filling list, and clearing it in OnNavigatedFrom(). Actually, i want to do the same for pivots - that's why i asked question in the near thread ( http://stackoverflow.com/questions/18895232/sending-loadingpivotitem-event-to-pivotitems-usercontrols ) – Vitalii Vasylenko Sep 19 '13 at 17:37
  • Just another small question: why yielding while returning? – Vitalii Vasylenko Sep 21 '13 at 19:46
  • 1
    that's because i return a enumerable, like this when you iterate through the response it basically return the item element by element – Benoit Catherinet Sep 21 '13 at 19:50
  • Googled for additional information, looking like very usefull stuff. – Vitalii Vasylenko Sep 21 '13 at 21:06