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:


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 in toolbar)
  2. When the code is paused, open the Immediate Window (another tab of Output by default)
  3. Write command into Immediate Window and pres Enter:
    
    GC.Collect();
    
    
  4. Garbage collection should be performed now and expected result is:
    
    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:


GC.Collect();
GC.WaitForPendingFinalizers();

Napsat komentář

Vaše e-mailová adresa nebude zveřejněna.