当我将此代码放在一个小型控制台项目中时:
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
在这里什么也不做。
那是为什么?