asp.net中gc的含义和作用
发布网友
发布时间:2022-03-28 16:24
我来回答
共1个回答
热心网友
时间:2022-03-28 17:53
GC 类 控制系统垃圾回收器(一种自动回收未使用内存的服务)。
GC 会跟踪托管内存中分配的对象,并且定期执行垃圾回收.当使用内存不能满足内容请求时,GC回收会自动进行,也可以使用Collect方法强制进行垃圾回收
例子:
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();
}
}
}
}
具体参开 msdn: https://msdn.microsoft.com/zh-cn/library/system.gc(v=vs.110).aspx
GC 源代码参考: http://referencesource.microsoft.com/#mscorlib/system/gc.cs,7abab96bebb051fd