当我将此代码放在一个小型控制台项目中时:
Console.WriteLine($"Mémoire avant allocation 1G: {GC.GetTotalMemory(false)}");
byte[] buf = new byte[1000000000];
Console.WriteLine($"Mémoire après allocation 1G: {GC.GetTotalMemory(false)}");
buf = null;
GC.Collect();
GC.WaitForPendingFinalizers();
GC.Collect();
Console.WriteLine($"Mémoire après libération 1G: {GC.GetTotalMemory(false)}");
我得到以下结果(如预期):
Mémoire avant allocation 1G: 30028 Mémoire après allocation 1G: 1000038252 Mémoire après libération 1G: 29472
现在我正在处理的大型应用程序中的代码非常相同,我得到了以下结果:
Mémoire avant allocation 1G: 153152496 Mémoire après allocation 1G: 1153152552 Mémoire après libération 1G: 1146813960
如您所见,GC.Collect
在这里不执行任何操作。
为什么?
尝试压缩LOH
GCSettings.LargeObjectHeapCompactionMode = GCLargeObjectHeapCompactionMode.CompactOnce;
GC.Collect( );
还请注意,描述GC.Collect( )
的文档始终使用单词“ tries”或“ try”。
示例(重点为我:):>
使用此方法try
回收所有不可访问的内存。它执行所有世代的阻塞垃圾收集。所有对象,无论它们在内存中已经存放了多长时间,都将考虑进行收集;但是,不收集托管代码中引用的对象。使用此方法将系统强制为try
以回收最大可用内存量。