Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is GC.Collect() blocking?

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.

like image 852
CodeAndCats Avatar asked Jun 18 '11 22:06

CodeAndCats


People also ask

What is GC collect () in Python?

Python deletes unwanted objects (built-in types or class instances) automatically to free the memory space. The process by which Python periodically frees and reclaims blocks of memory that no longer are in use is called Garbage Collection.

Should we call GC collect?

The general advice is that you should not call GC.

Is GC collect thread safe?

There is nothing wrong in calling GC. Collect in BackGround thread. In fact it doesn't makes any difference at all.


3 Answers

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();
like image 176
Maxim Avatar answered Oct 19 '22 13:10

Maxim


Since .NET Framework 4.5 you can specify whether the GC collection should be blocking:

GC.Collect(GC.MaxGeneration, GCCollectionMode.Optimized, blocking: true);

or

GC.Collect(GC.MaxGeneration, GCCollectionMode.Default, blocking: true);

GCCollectionMode.Default currently defaults to GCCollectionMode.Forced

For more details, see:

MSDN: GC.Collect Method (Int32, GCCollectionMode, Boolean)

MSDN: Induced collections - guide

like image 29
Shocked Avatar answered Oct 19 '22 11:10

Shocked


If you want to benchmark your code, it should be done over a course of many iterations and as an average. You are never guaranteed when GC is run in the first place.

like image 24
Daniel A. White Avatar answered Oct 19 '22 11:10

Daniel A. White