Reputation: 3076
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.
Upvotes: 2
Views: 1378
Reputation: 14896
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.
Upvotes: 2
Reputation: 3785
Yes . GC.collect() ensures garbage collection. But its not a good practice.
Ref : Best Practice for Forcing Garbage Collection in C#
Upvotes: 1