Reputation: 67
I've been working on a C#/WPF application for a little while now and I've gotten to the point where I think some of my objects are not being garbage collected as i would expect them to be.
How did I make this determination?
I've added finalizers with a break point in the classes I expect to be garbage collected. I run my application and trigger the series of events that would a) create the object and then b) cause the object to be condemned (in theory). For example, I open a dialog and then close it, etc. My finalizers are not being called.
Just to be extra sure that GC isn't taking an inordinately long time or that the objects somehow got promoted into and older generation and hence are not being collected at the same rate I even created a thread that periodically forces garbage collection i.e.:
System.GC.Collect();
System.GC.WaitForPendingFinalizers();
Still no finalizer breakpoints being hit. At this point I'm fairly certain that there is some reference preventing these objects from being collected but I can't for the life of me determine what.
So my question is two-fold:
Thanks in advance!
Upvotes: 4
Views: 1897
Reputation: 10708
By calling GC.Collect
and GC.WaitForPendingFinalizers
, you are ensuring the finalizers will kick off, but you also need to be sure that this code is calling. Breakingpoint it (or rather, the method closure right after WaitForPendingFinalizers
) to ensure that the code is being executed.
Since this is a WPF project, it may also be helpful to insert a "debug button" by having a PreviewKeyDown
in whatever view ou're working on, which cheks for a specific key and then breakpoints in an otherwise no-op if
. Putting your garbage collection code here should similarly ensure that your code is executing.
As mentioned, event handlers can also hard references, so be aware of everywhere you're using events, and realize that WPF hooks into PropertyChanged
quite a bit.
Upvotes: 0
Reputation: 17213
This may not be an exact answer to your question, as I can't see your code - but I find most commonly for me, when an object doesn't get garbage collected its usually because I have forgotten to unsubscribe from an event somewhere. When you subscribe to an event you do create a reference that will prevent your class from being collected.
On a side note, the garbage collector is a very unpredictable process. I remember reading somewhere that even if you call GC.Collect
it does not guarantee that your unreferenced class will get collected immediately.
Upvotes: 2