views:

782

answers:

3

Is there a way to trigger a garbage collection in a .NET process from another process or from inside WinDBG?

There are the Managed Debugging Assistants that force a collection as you move across a native/managed boundary, and AQTime seems to have button that suggests it does this, but I can't find any documentation on how to do it.

A: 

If you expose a function/object via remoting, that could be done quite easily.

leppie
The applications I'm interesting do it with don't support remoting at present and it would be infeasible to add it just for this.
Ian G
Why would a single exposed remotable object be unfeasible? You could do it with less than 20 lines. Here is a small example: http://xacc.svn.sourceforge.net/viewvc/xacc/xacc/Configuration/KickStart.cs?view=markup
leppie
Because it's a native C++ app that only accesses .net via COM, and while there's a lot of C# the amount that's guaranteed to be access where you could hook this is much smaller. There's non technical reasons too.
Ian G
+3  A: 

Well... there's the immediate window. If you have the luxury of attaching to the process, I supposed you could manually GC.Collect in the immediate window.

Bigger question: why would you want to manually induce GC.Collect? It's a nasty habit, and indicative of much bigger design issues.

David Hill
It's not something I'd intend to do often enough to be habitual :-). We occasionally have memory usage issues; when these occur the GC will be collecting frequently. When investigating it's preferable to use cut down data sets for speed reasons but these don't stress the GC in the same way. ...
Ian G
[Continued ...] One aspect of occasionally useful information when on the smaller sets is what proportion of the memory usage is potentially reclaimable by the GC. If the it's only one particular point then you can tweak the code to force, but occasionally more ad hoc methods would be convenient.
Ian G
I agree, I've used the GC.Collect for that purpose, usually while watching perfmon to see "what I can get back".Good on ya, seems like you're on the right side of the GC debate :)
David Hill
A: 

John Cocktoastan's answer to use GC.Collect when in Visual Studio is the best option if there.

I still can't find an alternative to actually do the collection under WinDBG but taking a step back to problem of "How much memory is reclaimable?" (see my comment to John's answer) I think there is an alternative by using a scripted (PowerDBG?) search via some combination of !DumpHeap and !GCRoot to find the non-rooted handles and total the space used (basically emulate the algorithm that the GC would do using the debugger). But since thinking of this I haven't had one of these bugs so haven't tried to write the code to do it.

Ian G