C# – Is GC.Collect() blocking

cgarbage-collection

I'm running some benchmark tests over my code and I want to make sure a garbage collect doesn't occur during one of my benchmarks because it's cleaning up the mess of a prior test. I figure my best chance of this is to force a collect before starting a benchmark.

So I'm calling GC.Collect() before a benchmark starts but not sure if a collect continues to run in a separate thread, etc and returns immediately. If it does run on a BG thread I want to know how to call it synchronously or a at least wait til it's finished the collect.

Best Answer

As MSDN states - Use this method to try to reclaim all memory that is inaccessible.

Anyway, if it does starts Garbage collection you should wait to all finilizers to finish before start benchmarking.

   GC.Collect();

   GC.WaitForPendingFinalizers();
Related Topic