1

I want to dispose of a control I'm dynamically adding to my app. The garbage collector is not picking up the object after I .Remove() it from its parent control, and it has huge bitmaps and geometry private members.

I want to be able to do something like this:

foreach (ScrollItem mylabel in canvas1.Children)
{
    if (mylabel.bRemove == true)
    {
        canvas1.Children.Remove(mylabel);
        mylabel = null;  // or mylabel.Dispose();
    }
}

canvas1 can't have null items in a UIObjectCollection so I can't set it to null, and if I just Remove() it the garbage collector doesn't collect it.

I tried to do something like:

myobj = mylabel;
canvas1.Children.Remove(mylabel);
myobj = null;

but that doesn't work either.

Adam
  • 15,537
  • 2
  • 42
  • 63
jeffbeat
  • 69
  • 1
  • 5
  • 1
    Have you wired up any events listeners to/from it? Those are often a cause for left over references thus preventing garbage cleanup. – Chris Sinclair Aug 13 '12 at 03:26
  • no, but I have it in a timer... where theres a call to this timer every 50ms or so, maybe the GC sees its still looking at (similar) objects – jeffbeat Aug 13 '12 at 05:48
  • I don't have much experience with WPF and dynamic controls, but don't you have to Dispose the dynamically created control? Also release any connections between the dynamically created control and the timer. Where is the timer? – Maarten Aug 13 '12 at 06:01
  • Yeah, try shutting down the timer; especially if it exists outside the control. Also, how are you tracking memory usage? Sometimes memory reported isn't exactly current/accurate. – Chris Sinclair Aug 13 '12 at 11:48

1 Answers1

4

As long as there is no references to your object the GC will collect it. Check your app for any additional references to your object. This can typically be event subscribers. You might want to use a .NET memory profiler too see what is preventing your object from beeing GC'ed.

sam1589914
  • 806
  • 4
  • 9