垃圾回收(GC)

(刚进入管理堆的对象称为0代对象)0代对象使用空间阈值为256KB
如果有新对象使得超过阈值,那么就会导致启动GC.经过GC回收之后剩下的对象叫1代对象.此时0代就为空了,那么后面新分配的对象将会在0代空间。1代阈值为2MB。在默认情况下(未超过1代阈值时)GC会忽略1代对象去直接回收0代对象,因为GC会假定越新的对象其生命周期越短,此处应该是先检查0代对象,然后检查1代阈值是否超过,未超过则忽略检查。

2代阈值约为10M左右。
管理堆只支持0代、1代、2代。(没有3代,可通过GC.MaxGeneration来获得最大代数2)
GC会自己调整阈值来优化性能.例如:如果你短时间内构造了大量的短生命周期对象,此时GC会从0代回收大量内存,此时GC可能会调整0代的阈值从256KB到128KB.(如果要回收0代所有的对象,GC不会一个个回收,它会简单的设置NxetObjPtr指向0代的开始处),同样如果GC从0代未回收任何对象,那么它会调整阈值到512KB.对于1代、2代也是如此。

GC.Collect(Int32 Generation),该方法可以指定哪代被回收。0表示0代被回收,1表示0、1代被回收,2表示2、1、0被回收。

Code:

using System;

class GenObj
{
    ~GenObj()
    {
        Console.WriteLine("In Finalize method");
    }
}
class App
{
    static void Main()
    {
        Console.WriteLine("Maximum generations: " + GC.MaxGeneration);
        // Create a new BaseObj 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.Collect();
        Console.WriteLine("Gen " + GC.GetGeneration(o)); // 2
        GC.Collect();
        Console.WriteLine("Gen " + GC.GetGeneration(o)); // 2 (max)
        o = null; // Destroy the strong reference to this object.
        Console.WriteLine("Collecting Gen 0");
        GC.Collect(0); // Collect generation 0.
        GC.WaitForPendingFinalizers(); // Finalize is NOT called.
        Console.WriteLine("Collecting Gen 1");
        GC.Collect(1); // Collect generation 1.
        GC.WaitForPendingFinalizers(); // Finalize is NOT called.
        Console.WriteLine("Collecting Gen 2");
        GC.Collect(2); // Same as Collect()
        GC.WaitForPendingFinalizers(); // Finalize IS called.
        Console.ReadKey();
    }
}

输出:

Maximum generations: 2
Gen 0
Gen 1
Gen 2
Gen 2
Collecting Gen 0
Collecting Gen 1
Collecting Gen 2
In Finalize method

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值