GC.GetTotalMemory方法
方法描述:
获取目前所有受控代码分配的字节数。带有一个参数,bool值,用来标识是否先进行垃圾收集再计算字节数。
命名空间:System
Assembly:mscolib.dll
方法签名:
public static long GetTotalMemory(bool forceFullCollection)
参数说明:
forceFullCollection
类型:System.Boolean
true表示该方法先做垃圾收集操作,之后才计算出受控代码分配的字节数。false表示不做垃圾收集,直接计算出受控代码分配的字节数。
返回值:
类型:System.Int64
返回目前所有受控代码所分配的最大可能的一个近似值。
注意:
如果参数forceFullCollection为true的话,该方法内部先做垃圾收集,时间的长短跟垃圾的多少有关系,并且该垃圾收集不保证所有不可访问的对象都能够被回收。
例子:
输出结果:
the highest generation is 2
Generation:0
Total Memory:519676
Generation:1
Total Memory:196004
Generation:2
Total Memory:195764
方法描述:
获取目前所有受控代码分配的字节数。带有一个参数,bool值,用来标识是否先进行垃圾收集再计算字节数。
命名空间:System
Assembly:mscolib.dll
方法签名:
public static long GetTotalMemory(bool forceFullCollection)
参数说明:
forceFullCollection
类型:System.Boolean
true表示该方法先做垃圾收集操作,之后才计算出受控代码分配的字节数。false表示不做垃圾收集,直接计算出受控代码分配的字节数。
返回值:
类型:System.Int64
返回目前所有受控代码所分配的最大可能的一个近似值。
注意:
如果参数forceFullCollection为true的话,该方法内部先做垃圾收集,时间的长短跟垃圾的多少有关系,并且该垃圾收集不保证所有不可访问的对象都能够被回收。
例子:
- using System;
- namespace GCCollectIntExample
- {
- class MyGCCollectClass
- {
- private const long maxGarbage = 1000;
- static void Main()
- {
- MyGCCollectClass myGCCol = new MyGCCollectClass();
- // Determine the maximum number of generations the system
- // garbage collector currently supports.
- Console.WriteLine("The highest generation is {0}", GC.MaxGeneration);
- myGCCol.MakeSomeGarbage();
- // Determine which generation myGCCol object is stored in.
- Console.WriteLine("Generation: {0}", GC.GetGeneration(myGCCol));
- // Determine the best available approximation of the number
- // of bytes currently allocated in managed memory.
- Console.WriteLine("Total Memory: {0}", GC.GetTotalMemory(false));
- // Perform a collection of generation 0 only.
- GC.Collect(0);
- // Determine which generation myGCCol object is stored in.
- Console.WriteLine("Generation: {0}", GC.GetGeneration(myGCCol));
- Console.WriteLine("Total Memory: {0}", GC.GetTotalMemory(false));
- // Perform a collection of all generations up to and including 2.
- GC.Collect(2);
- // Determine which generation myGCCol object is stored in.
- Console.WriteLine("Generation: {0}", GC.GetGeneration(myGCCol));
- Console.WriteLine("Total Memory: {0}", GC.GetTotalMemory(false));
- Console.Read();
- }
- void MakeSomeGarbage()
- {
- Version vt;
- for (int i = 0; i < maxGarbage; i++)
- {
- // Create objects and release them to fill up memory
- // with unused objects.
- vt = new Version();
- }
- }
- }
- }
the highest generation is 2
Generation:0
Total Memory:519676
Generation:1
Total Memory:196004
Generation:2
Total Memory:195764