Triggering a .NET garbage collection externally

2019-06-15 02:00发布

问题:

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.

回答1:

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.



回答2:

Answered in another question :

Basically, use PerfView:

PerfView.exe ForceGC [ProcessName | Process ID] /AcceptEULA

It's not intended for production use.



回答3:

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.



回答4:

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