2

I see some people asked about GC.Collect(), for example:

  1. When is it acceptable to call GC.Collect?

  2. GC.Collect()

  3. What's so wrong about using GC.Collect()?

I see that in general, people say: CG is smart enough to collect garbage on it own, premature optimization is bad.

But according to the document:

Use this method to try to reclaim all memory that is inaccessible. It performs a blocking garbage collection of all generations.

All objects, regardless of how long they have been in memory, are considered for collection; however, objects that are referenced in managed code are not collected. Use this method to force the system to try to reclaim the maximum amount of available memory.

So I see that this GC.Collect() command only delete the data that is no longer used, I can't think of any risk that it may cause, so what is the risk of calling GC.Collect()? Is it bad for the PC's hardware?

123iamking
  • 2,387
  • 4
  • 36
  • 56
  • 3
    The only risk is the potential for adverse performance if done incorrectly. It won't damage anything. – itsme86 Jun 27 '18 at 16:17
  • I can't comment yet, but this may help you. https://stackoverflow.com/questions/233596/best-practice-for-forcing-garbage-collection-in-c-sharp – Gavin Jun 27 '18 at 16:17
  • @Gavin It's weird to post a comment saying you can't comment. – itsme86 Jun 27 '18 at 16:24
  • @itsme86 magic that converts trivial answers to a comment ... see https://meta.stackoverflow.com/questions/367433/minimum-50-reputation-to-post-comments-can-be-circumvented-by-posting-a-trivial/367447#367447 – rene Jun 27 '18 at 16:26
  • thanks, but is there a practical scenario that more understandable? I read Ricom's example about Gen: https://blogs.msdn.microsoft.com/ricom/2003/12/02/two-things-to-avoid-for-better-memory-usage/ , but it's pretty vague that I can't imagine. – 123iamking Jun 28 '18 at 03:16
  • Things have moved on since older answers @rene I think? As of .NET 4.6 we have GC.TryStartNoGCRegion where you might attempt to disable GC for a critical code path. So before doing this you might consider forcing a collection. Same goes for working with GCLatencyMode.LowLatency. Even without using those, it is sometimes used when you are aware things a quiet before entering some heavy work. – Ben Hall Jun 30 '18 at 09:10
  • @BenHall it is not clear to me this question is specifically about those features. The preferred way would be to either add an updated answer to the dupe OR edit this question to make it explicitly about this newest context. If you prefer the latter and the OP agrees I'm happy to reopen after the question is edited. Let me know when that is done. – rene Jun 30 '18 at 09:19

0 Answers0