CG.Collect在我的大型应用程序中不起作用,但是在小型项目中可以正常工作

当我将此代码放在一个小型控制台项目中时:

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在这里什么也不做。

那是为什么?

fanxin8798 回答:CG.Collect在我的大型应用程序中不起作用,但是在小型项目中可以正常工作

尝试压缩LOH

GCSettings.LargeObjectHeapCompactionMode = GCLargeObjectHeapCompactionMode.CompactOnce;
GC.Collect( );

还要注意,描述GC.Collect( )的文档始终使用单词“ tries”或“ try”。

示例(重点是我的):

使用此方法 尝试 来回收所有无法访问的内存。它执行了所有世代的阻塞垃圾收集。

所有对象,无论它们在内存中已经存放了多长时间,都将被考虑收集;但是,不收集托管代码中引用的对象。使用此方法可以强制系统 尝试 来回收最大可用内存量。

本文链接:https://www.f2er.com/2432828.html

大家都在问