Direct useCodeAnd comment out the problem ~~
Code
Public Static Class Program
{
Internal Sealed Class Genobj
{
~ Genobj ()
{
Console. writeline ( " In Finalize method " );
}
}
Public Static Void Main ()
{
Console. writeline ( " Maximum generations: " + GC. maxgeneration );
// Create a new genobj In the heap.
Object o = New Genobj ();
// Because this object is newly created, it is in generation 0.
Console. writeline ( " Gen " + GC. getgeneration (o )); // 0 this method is used to obtain the number of generations of Objects
// Parameter A Garbage Collection Promotes the object's generation.
GC. Collect ();
Console. writeline ( " Gen " + GC. getgeneration (o )); // 1. The unit that remains alive after GC is upgraded.
GC. Collect ();
Console. writeline ( " Gen " + GC. getgeneration (o )); // 2. The unit that remains alive after GC is upgraded.
GC. Collect ();
Console. writeline ( " Gen " + GC. getgeneration (o )); // 2 (max) The unit that remains alive after each GC is upgraded to a maximum of 2 --#
O = Null ; // Remove strong reference relationships
Console. writeline ( " Collecting Gen 0 " );
GC. Collect ( 0 ); // Collect generation 0. Reclaim the memory of the specified generation
GC. waitforpendingfinalizers (); // Finalize is not called.
Console. writeline ( " Collecting gens 0, and 1 " );
GC. Collect ( 1 ); // Collect generations 0 & 1.
GC. waitforpendingfinalizers (); // Finalize is not called.
Console. writeline ( " Collecting gens 0, 1, and 2 " );
GC. Collect ( 2 ); // Same as collect ()
GC. waitforpendingfinalizers (); // Finalize is called. This object is completely replaced ....
}
}
The first time I felt that the Finalize of an object had to wait so long ....
Of course, if the zero-generation object is recycled, it will not be so troublesome.
--#
PS: simple logic of GC:
1. Traverse generation 0 useless to pull out and kill, and use upgrades to generation 1,
2. If the space already exists, it will not be recycled.
3. If the space is not enough or the generation 1 is full, pull out G1 useless and burn it to the day, and upgrade it to G2.
4. If it is necessary to continue G2. .. If G2 is not enough, outofmemoryexception ....
Parameters:
When the GC Initialization is complete, the size of generation 0 is determined to be 256 kb (priority is given to L2 cache)
The starting value of Generation 1 is 0. The maximum value is 2 MB.
Generation 2 is unlimited