The question is just for research purposes.
I've read many books about C# and this question always comes to my mind. What I understood that C# is managed code and all garbage collection occurs when CLR decides when to run garbage collection. Let's start.
Let's imagine that I have simple class Student
:
public class Student
{
public int IdStudent { get; set; }
public string Name { get; set; }
public string Surname { get; set; }
}
class Program
{
static void Main(string[] args)
{
This is row1: Person person = new Person() {IdPerson=1, Name="Bill", SurName="Collins"};
This is row2: System.GC.Collect();
This is row3: string str="Hello World!";
}
}
Please, approve or reject my suppositions:
- Am I right that garbage collection is not run immediately at row2?
GC.Collect()
is just a request to make a garbage collection which DOES NOT RUN IMMEDIATELY at row2. This row maybe executed in x milliseconds/seconds. In my view, methodSystem.GC.Collect();
just says to garbage collector that garbage collector should run garbage collection, but real garbage collection may occur in x milliseconds/secondsOnly garbage collector knows when garbage collection will be run. And If there is free space in Generation 0, then garbage collection will not occur in the row2:
row2: System.GC.Collect();
It is not possible to run garbage collection immediately as we are programming in managed environment and only CLR decides when to run garbage collection. Garbage collection can be run in x milliseconds/seconds or garbage collection maybe not run cause there is enough space in generation 0 to create new objects after calling method
GC.Collect()
. What programmer can do is just ask CLR to run garbage collection by methodGC.Collect()
.
Update:
I've read this msdn article about GC.Collect Method ()
.. However, it is unclear to me when real clearing of unreferenced objets is started. MSDN says:
GC.Collect Method () forces an immediate garbage collection of all generations.
However, in Remarks I've read this one:
Use this method to try to reclaim all memory that is inaccessible. It performs a blocking garbage collection of all generations.
- I am confused by this "Use this method to TRY" and I think that garbage collection may not occur cause CLR decides that there is enough space to create new objects. Am I right?