CLR via C# 讀書筆記 5-6 記憶體回收的Generation

來源:互聯網
上載者:User

直接用代碼和注釋說明問題吧~~

 

代碼

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 這個方法是用來擷取對象在第幾代

// Performing a garbage collection promotes the object's generation.
GC.Collect();
Console.WriteLine("Gen " + GC.GetGeneration(o)); // 1 每次GC以後還存活的單位就升級
GC.Collect();
Console.WriteLine("Gen " + GC.GetGeneration(o)); // 2 每次GC以後還存活的單位就升級
GC.Collect();
Console.WriteLine("Gen " + GC.GetGeneration(o)); // 2 (max) 每次GC以後還存活的單位就升級 最高只有2級 - -#

o = null; // 移除強參考關聯性
Console.WriteLine("Collecting Gen 0");
GC.Collect(0); // Collect generation 0. 回收指定代的記憶體
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. 這裡這個對象才被徹底做掉了....
}

}

 

第一次感覺一個對象的Finalize要等這麼久....

當然,如果在0代對象的時候就被回收了 就沒這麼麻煩了

- -#

 

 

PS:GC的簡單邏輯:

  1.遍曆Generation 0  沒用的拉出去殺掉,還有用的升級到Generation 1 ,

  2.如果空間已經過了, 就不繼續回收了 ,返回

  3.如果空間還不夠或者Generation 1 也滿了, 把G1沒用的拉出去燒了祭天,然後還活著的升級到G2

  4.如果有必要 繼續回收G2...如果g2也不夠了 那麼就OutOfMemoryException ....

  

參數:

GC在初始化完成的時候Generation 0 的大小就確定為256k (優先考慮放在L2 Cache中)

Generation 1 開始大小是0  最大可以到2M

Generation 2  沒有限制

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.