12

I read many things about garbage collection like it's generation, scope etc but want to know when does the garbage collection gets triggered ? an example will be really helpful if possible.

Thanks,

Uyghur Lives Matter
  • 18,820
  • 42
  • 108
  • 144
  • 3
    I don't have enough points, @MikeNakis :) – Nikolay Kostov Feb 11 '15 at 18:39
  • 4
    It would be helpful to know *why* you want to know. The GC does a collection when it feels like it's a good time to do a collection; its internal policies are not part of the documented, guaranteed behavior. If you're just curious, that's one thing. If you intend to develop software that depends on a particular GC policy, you are skating on some pretty thin ice. – Eric Lippert Feb 11 '15 at 22:49
  • 3
    @EricLippert - recently i was asked this question in interview..so want to know. –  Feb 12 '15 at 00:44

3 Answers3

16

Garbage collection occurs when one of the following conditions is true:

  • The system has low physical memory.
  • The memory that is used by allocated objects on the managed heap surpasses an acceptable threshold. This threshold is continuously adjusted as the process runs.
  • The GC.Collect method is called. In almost all cases, you do not have to call this method, because the garbage collector runs continuously. This method is primarily used for unique situations and testing.

Source: Fundamentals of garbage collection - Conditions for a garbage collection

Theodor Zoulias
  • 34,835
  • 7
  • 69
  • 104
Nikolay Kostov
  • 16,433
  • 23
  • 85
  • 123
  • 2
    so.. does clr check for physical memory at regular intervals in program and if it is low , GC is called ? –  Feb 11 '15 at 18:32
  • 1
    Most probably, yes. If Microsoft says that GC is called when the system has low memory, the CLR should be notified or checking if the memory is low. – Nikolay Kostov Feb 11 '15 at 18:34
1
  1. Automatically when the application is unable to acquire memory from managed heap
  2. Automatically when a given AppDomain unloads from memory
  3. through code when GC.Collect() called
Peter Csala
  • 17,736
  • 16
  • 35
  • 75
0

You are not in control of GC and can not reliably predict its behavior. All calls, like GC.Collect are simple messages to VM to start collection, but that does not mean that collection will eventually start right after the line.

Tigran
  • 61,654
  • 8
  • 86
  • 123