2

In Java, we can use the method System.gc() to suggest a GC. Today I got to know the method GC.Collect() in C# from this link. But the explanation is somewhat unclear to me.

The first line.

Forces an immediate garbage collection from generation 0 through a specified generation.

And the other line.

Use this method to try to reclaim memory that is inaccessible.

In my simple test code, GC.Collect() works immediately.

Console.WriteLine("abcdefg");
GC.Collect(2);
GC.Collect(2);
Console.WriteLine(GC.GetGeneration("abcdefg"));

GC.Collect() always forces a GC immediately?

Or just a suggestion like in Java?

This is not a question about "I want to force a GC in C#", I just want to know how it works.

Jenix
  • 2,996
  • 2
  • 29
  • 58
  • 2
    It will _force_ a garbage collection, which will _try to_ reclaim memory. So you're doing it right now, but the GC will still decide what to collect. – Pierre-Luc Pineault Oct 03 '15 at 18:22

2 Answers2

2

GC.Collect() forces GC immediately. Your thread will be blocked until the GC is finished.

About the "try to reclaim memory" part - if an object implements Finalize method, the finalizer has to run before the memory can be reclaimed. The garbage collector will schedule the finalizer to run, and the object will be kept in memory at least till the next GC.

Jakub Lortz
  • 14,616
  • 3
  • 25
  • 39
  • Thanks, I accepted this answer for the additional explanation. It makes sense why it said 'try to'. – Jenix Oct 03 '15 at 21:41
1

Yes . GC.collect() ensures garbage collection. But its not a good practice.

Ref : Best Practice for Forcing Garbage Collection in C#

Community
  • 1
  • 1
Rahman
  • 3,755
  • 3
  • 26
  • 43