Ok this is potentially a noob question but here goes.
Is it possible to “outrun” the garbage collector?
The reason I ask is because I have a recursive method that gets run several times during some event in my application (by several I mean around 60 times per second and the event goes on for an indefinite amount of time, even minutes). The problem is that in each loop of the recursive method, I create a fairly complex object (TreeViewItem with some mods we need for the project AND another complex object that works as the DataContext for the TreeViewItem), so my concern is that these TreeViewItems stay in the heap when the recursive method runs, so when the garbage collector kicks in, it doesn’t clean them; and possibly, the next time the recursive method starts, it stacks some more TreeViewItem, and the garbage collector never catches up.
The problem is that we have a memory leak, and we’re looking for the culprit.
Any help really appretiated
No, you can’t make the garbage collector leak by overloading it.
The way that the garbage collector works actually makes it handle situations like yours rather well.
If you remove a reference to a large complex of objects, it will not collect the objects one at a time. It sees that none of the objects have any active references any more and it will collect the whole bunch of objects at once.
Most objects are short lived, so the garbage collector is built to handle that efficiently. If you for example have filled the first generation heap, and 90% of the objects are to be collected, the garbage collector doesn’t remove the 90%. Instead it moves the 10% to the next generation and simply wipes the first generation.
If the garbage collector still finds itself with a lot of work to do, it will just do it, and you will have to wait for it. It freezes your threads while it’s working, and they simply won’t run until the garbage collector is done.