In my application there is a specific time when a number of large objects are all released at once. At that time I would like to do a garbage collection on specifically the large object heap (LOH).
I'm aware that you cannot do that, you must call GC.Collect(2)
because the GC is only invoked on the LOH when it is doing a generation 2 collection. However, I've read in the documentation that calling GC.Collect(2)
would still run a GC on generations 1 and 0.
Is it possible to force the GC to only collect gen 2, and not include gen 1 or gen 0?
If it is not possible, is there a reason for the GC to be designed that way?
It's not possible. The GC is designed so that a generation 2 collection always also collects generation 0 and 1.
Edit: Found you a source for this on a GC developer's blog:
Gen2 GC requires a full collection (Gen0, Gen1, Gen2 and LOH! Large objects are GC’ed at every Gen2 GC even when the GC was not triggered by lack of space in LOH. Note that there isn’t a GC that only collects large objects.) which takes much longer than younger generation collections.
Edit 2: From the same blog's Using GC Efficiently Part 1 and Part 2 apparently Gen0 and Gen1 collections are fast compared to a Gen2 collection, so that it seems reasonable to me that only doing Gen2 wouldn't be of much performance benefit. There might be a more fundamental reason, but I'm not sure. Maybe the answer is in some article on that blog.