none
GC.Collect collects instantly or not? RRS feed

  • Question

  • Hi, my question is, will the Garbage Collector start collecting (or starts tracing) instantly after calling GC.Collect?
    Lots of forums and discussions say that it will not, rather it will start automatically when there is not enough memory to allocate new objects. If this is the scenario, what is this GC.Collect() all about? Anyway even if we dont call GC.Collect() GC will start collecting when there is no enough memory.

    Also i have seen like, when ever i call GC.Collect() and then check the CollectionCount property of GC it is incremented by one. So thats makes me feel like it Collects instantly. Also the following code, is said to free all the unused memory...

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

    If GC will not start instantly how can the above pattern guarentee a full collection?

    So please help me, all the other forums are making me confused only, will it start instantly??
    Wednesday, October 8, 2008 9:39 AM

Answers

  • It collects instantly, it won't return until the collection is completed.  What you quoted is the normal behavior of the garbage collector, what it does when you don't call GC.Collect() explicitly.  Don't help, it knows what to do and when to do it.  Helping prevents it from doing the optimum job.
    Hans Passant.
    • Marked as answer by Aldo John Wednesday, October 8, 2008 11:18 AM
    Wednesday, October 8, 2008 11:02 AM
    Moderator

All replies

  • It collects instantly, it won't return until the collection is completed.  What you quoted is the normal behavior of the garbage collector, what it does when you don't call GC.Collect() explicitly.  Don't help, it knows what to do and when to do it.  Helping prevents it from doing the optimum job.
    Hans Passant.
    • Marked as answer by Aldo John Wednesday, October 8, 2008 11:18 AM
    Wednesday, October 8, 2008 11:02 AM
    Moderator
  • Thanks for the answer...
    Wednesday, October 8, 2008 11:19 AM