user3265575
user3265575

Reputation:

When does garbage collection get triggered in C#?

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,

Upvotes: 15

Views: 16727

Answers (3)

Nikolay Kostov
Nikolay Kostov

Reputation: 16983

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

Upvotes: 21

user16974793
user16974793

Reputation: 11

  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

Upvotes: 1

Tigran
Tigran

Reputation: 62265

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.

Upvotes: 0

Related Questions