Ask a questionAsk a question
 

AnswerHow do i dispose of Image / BitmapImage

  • Sunday, March 30, 2008 7:50 AMZuchman Users MedalsUsers MedalsUsers MedalsUsers MedalsUsers Medals
     

    Hello all of you nice people.

    I'm writing application in C# WPF, and using BitmapImage (System.Windows.Media.Imaging.BitmapImage) and Image (System.Windows.Controls.Image).

    Now, I'm allocating 1000 images (that uses this nice and friendly BitmapImage), and see how my application memory usage is growing in like 20 M. Very good.

     

    The problem is when I try to free those images. All of the images are being contained in a container (WrapPanel) and when I remove them from the panel, the memory isn't free. (though, the images are not visible anymore).

     

    I made a nasty trick. I created a class with the original name "MyImage" that extends (Sorry, last year I worked with Java), and override the destructor, just to figure out that it is almost never being called, execpt when I close the application.

     

    When I'm trying to clear the images when the application still running, after few moments - I get from the destructor only  few calls out of 1000, and none of them releases any memory.

     

    Does anyone knows what I'm doing wrong?

    tnx,

    Good day

Answers

  • Monday, March 31, 2008 12:11 AMDr. WPF Users MedalsUsers MedalsUsers MedalsUsers MedalsUsers Medals
     Answer

    Assuming there are no outstanding rooted references for the BitmapImage objects, the CLR will reclaim the memory when it needs it.

     

    You don't need to add a destructor to know whether the images are being freed.  This actually aggravates the problem by promoting your object to a higher generation (because it is more costly to free the object).

     

    See my response in this thread for a method of tracking lifetime that is based on maintaining weak references to the objects.  Also see that thread for a recommendation of a memory profiler that can be used to track object leaks (which will be your next step if you truly do have outstanding rooted references).

     

All Replies

  • Monday, March 31, 2008 12:11 AMDr. WPF Users MedalsUsers MedalsUsers MedalsUsers MedalsUsers Medals
     Answer

    Assuming there are no outstanding rooted references for the BitmapImage objects, the CLR will reclaim the memory when it needs it.

     

    You don't need to add a destructor to know whether the images are being freed.  This actually aggravates the problem by promoting your object to a higher generation (because it is more costly to free the object).

     

    See my response in this thread for a method of tracking lifetime that is based on maintaining weak references to the objects.  Also see that thread for a recommendation of a memory profiler that can be used to track object leaks (which will be your next step if you truly do have outstanding rooted references).