Force Garbage Collector during debugging in Visual Studio

Sometimes you need to check your .NET project’s memory management, but how to purge Garbage Collector during debugging from Visual Studio?

It’s really easy to force Garbage Collector to collect dead objects from heap.

All you need is command:

1
GC.Collect()

From Visual Studio during debugging

  1. As first your application needs to be paused. This can be done when code reaches breakpoint, or you can use Break All function (Ctrl+Alt+Back or blue pause icon blue pause icon in Visual Studio in toolbar)
  2. When the code is paused, open the Immediate Window (another tab of Output by default) Write command into Immediate Window and press Enter:
1
GC.Collect();

Garbage collection should be performed now and expected result is:

1
2
GC.Collect();
Expression has been evaluated and has no value

From code during runtime

You should not to care about GC in application – .NET runtime do it instead of you.

But in case you really need it, you can call GC by:

1
2
GC.Collect();
GC.WaitForPendingFinalizers();
comments powered by Disqus
Built with Hugo
Theme Stack designed by Jimmy