static void Main(string[] args)
{
Console.WriteLine("当前托管堆上分配了{0}K字节内存空间。", (GC.GetTotalMemory(false) / 1024).ToString());
Console.WriteLine("输入系统最大支持{0}代。\n", (GC.MaxGeneration + 1).ToString());
var obj = new { num = 1, txt = "abc" };
Console.WriteLine("obj创建完成,所引用对象当前为第{0}代。\n", GC.GetGeneration(obj).ToString());
//对第0代进行强制回收,所有对象终结前挂起当前进程
GC.Collect(0);
GC.WaitForPendingFinalizers();
Console.WriteLine("第{0}代强制回收完成。");
getmsg(obj);
GC.Collect();
GC.WaitForPendingFinalizers();
Console.WriteLine("所有代强制回收完成。");
getmsg(obj);
obj = new { num = 1, txt = "abc" };
Console.WriteLine("\nobj对象被赋予了同匿名类型的新实例。");
getmsg(obj);
for (int i = 0; i < 3; i++)
{
Console.WriteLine("第{0}代已经被收回了{1}次。", i, GC.CollectionCount(i));
}
Console.ReadKey();
}
static void getmsg(object o)
{
string objgen = GC.GetGeneration(o).ToString();
Console.WriteLine("obj所引用对象当前为第{0}代。\n", objgen);
}
{
Console.WriteLine("当前托管堆上分配了{0}K字节内存空间。", (GC.GetTotalMemory(false) / 1024).ToString());
Console.WriteLine("输入系统最大支持{0}代。\n", (GC.MaxGeneration + 1).ToString());
var obj = new { num = 1, txt = "abc" };
Console.WriteLine("obj创建完成,所引用对象当前为第{0}代。\n", GC.GetGeneration(obj).ToString());
//对第0代进行强制回收,所有对象终结前挂起当前进程
GC.Collect(0);
GC.WaitForPendingFinalizers();
Console.WriteLine("第{0}代强制回收完成。");
getmsg(obj);
GC.Collect();
GC.WaitForPendingFinalizers();
Console.WriteLine("所有代强制回收完成。");
getmsg(obj);
obj = new { num = 1, txt = "abc" };
Console.WriteLine("\nobj对象被赋予了同匿名类型的新实例。");
getmsg(obj);
for (int i = 0; i < 3; i++)
{
Console.WriteLine("第{0}代已经被收回了{1}次。", i, GC.CollectionCount(i));
}
Console.ReadKey();
}
static void getmsg(object o)
{
string objgen = GC.GetGeneration(o).ToString();
Console.WriteLine("obj所引用对象当前为第{0}代。\n", objgen);
}