Dave
Dave

Reputation:

Memory leaks in WPF/C#

Please note this is done in WPF/C# and not in .net2.0 Winforms

I have a ListBox which contains objects of say Class X. Class X contains a BitmapSource object which is displayed in the listbox, so it displays similar to [Image] [Text]

This is loaded via the use of the CreateBitmapSourceFromHBitmap - note also that I call DeleteHBitmap to delete the handle of the HBitmap during this call, which is well known to do from posts I've seen on google/etc

I have a tree which contains said ListBox in each TreeViewItem - typically the tree has several items loaded. Users can drag/drop these images into different TreeViewItems. To handle these operation I manually call the operations:

<code>
    ItemCollection.RemoveAt
</code>

<code>
    ItemCollection.Insert
</code>

to move the images from the ListBox item collection, note when I insert I create a new Class X object to insert into the ListBox item collection

I have noticed I get a consistent memory leak from calling such operations several times, over the space of 5-10 mins of consistent dragging and dropping.

My question is:

Am I handling the moving of the BitmapSource's correctly? Is there something I'm doing to cause the Images to not be fully removed from the ItemCollection?

Or is there something fundamental I've missed?

Upvotes: 6

Views: 1328

Answers (1)

mandel
mandel

Reputation: 2947

Which is the definition of the variable that holds the image in you ClassX??? The problem may be in the fact that you are creating a new ClassX and the old one is no being deleted by the GC making the head have two different instance of ClassX.

Since you are using unmanged code (CreateBitmapSourceFromHBitmap) you should check if all the finalize method are correctly called (though close or dispose probably) and that the are no static references that can be pointing to your ClassX.

Remember that if you ClassX is not removed the Bitmap instance will be reachable in the graph made by the GC making it not to remove it from the heap.

I recommned using perfmon and add the .Net memory object to see if there are any object that survived finalize or pinned object, those are the one you are probably interested regarding the memory leak.

I hope it helps :P, but it will be nicer if you put the code of the ClassX.

Upvotes: 1

Related Questions