GC.GetTotalMemory(false) 与容器内存工作集问题(Azure AKS、.NET Core 5)

GC.GetTotalMemory(false) vs Container Memory Working Set question (Azure AKS, .NET Core 5)

我在 Azure Kubernetes 服务中有一个带有 dotnet 核心应用程序 运行 的容器。 Pod 规范中未指定内存限制。

问题是为什么 GC.GetTotalMemory(false) 显示大约。使用了 3 Gb 的内存,而 AKS Insights 显示此 Pod 容器的内存为 9.5 GB?

运行 top 揭示了这 9.5 GB:

why GC.GetTotalMemory(false) shows approx. 3 Gb of memory used while AKS Insights shows 9.5 GB for this Pod container?

GC.GetTotalMemory(false) 是为 POD 中的垃圾收集器定义的。该参数定义是否在 运行 或 not.The 之前等待完全垃圾回收发生。近似值设置为 3GB,您也可以更改它。

下面example演示了如何使用GetTotalMemory方法获取和显示当前在托管内存中分配的字节数。

Parameters

forceFullCollection

Type: System.Boolean true to indicate that this method can wait for garbage collection to > occur before returning; otherwise, false.

diff 仍然为 0 的原因可能是因为即使您通过 false 也已经发生了 GC。

参考:What is the Difference between GC.GetTotalMemory(false) and GC.GetTotalMemory(true) and MS Document

据我了解 GC.GetTotalMemory(false) returns 托管对象的大小(以字节为单位),但整个工作内存集要大得多,因为内存是按页分配的,而且托管堆碎片,而且 GC 是未执行。