You need to enable JavaScript to run this app. .NET Core中如何提升进程实际物理内存占用以测试容器自动扩缩容
优惠活动
大模型
产品
解决方案
定价
更多

.NET Core中如何提升进程实际物理内存占用以测试容器自动扩缩容

问题根因

现代操作系统默认使用按需分页的内存管理机制:你调用Marshal.AllocHGlobal分配非托管内存、或是用new byte[]分配托管数组时,操作系统仅为进程预留了虚拟地址空间、标记对应内存为已提交状态,并没有实际分配物理内存页。只有当你对这块内存执行读写操作时,操作系统才会完成物理页的映射,物理内存占用才会真正上涨。你之前的代码仅做了内存分配、没有写入操作,自然只会提升提交内存数值,物理内存不会变化。

修复后的可运行代码

你只需要在分配内存后追加写入逻辑,强制触发物理页映射即可,同时可以将内存统计属性替换为WorkingSet64直接查看物理内存占用:

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Threading;

namespace MemoryAbuser
{
    class Program
    {
        private const int MIN_MB_TO_USE = 5000;
        private const int DURATION_IN_SECONDS = 20;

        private static List<IntPtr> memoryPointers = new ();
        private static List<byte[]> usedMemory = new ();

        static void Main(string[] args)
        {
            SetResources((ConsumptionStrategy)Enum.Parse(typeof(ConsumptionStrategy), args[0]));
        }

        private static void SetResources(ConsumptionStrategy consumptionStrategy)
        {
            AllocateMemory(consumptionStrategy);
            Thread.Sleep(DURATION_IN_SECONDS * 1000);
            DeAllocateMemory();
        }

        static void AllocateMemory(ConsumptionStrategy strategy)
        {
            Console.WriteLine($"物理内存占用 = {GetMemoryUsage()}");

            var sw = new Stopwatch();
            sw.Start();

            const int ONE_MEGABYTE = 1024 * 1024;
            const int BLOCK_SIZE = ONE_MEGABYTE * 10;

            long minBytesToUse = ONE_MEGABYTE * (long)MIN_MB_TO_USE;

            while (GetMemoryUsage() < minBytesToUse)
            {
                switch (strategy)
                {
                    case ConsumptionStrategy.ByteArray: 
                        var arr = new byte[BLOCK_SIZE];
                        // 按页大小写入即可,不需要写满全部字节,兼顾分配效率
                        for (int i = 0; i < BLOCK_SIZE; i += 4096) 
                        {
                            arr[i] = 0;
                        }
                        usedMemory.Add(arr); 
                        break;
                    case ConsumptionStrategy.AllocHGlobal: 
                        var ptr = Marshal.AllocHGlobal(BLOCK_SIZE);
                        // 写入数据强制触发物理页分配
                        for (int i = 0; i < BLOCK_SIZE; i += 4096)
                        {
                            Marshal.WriteByte(ptr + i, 0);
                        }
                        memoryPointers.Add(ptr); 
                        break;
                }
            }

            Console.WriteLine($"物理内存占用 = {GetMemoryUsage()}");
            Console.WriteLine($"内存分配耗时: {sw.Elapsed.TotalSeconds}秒");
        }

        static void DeAllocateMemory()
        {
            usedMemory.Clear();

            foreach (var memoryPointer in memoryPointers)
            {
                Marshal.FreeHGlobal(memoryPointer);
            }

            GC.Collect();
            GC.WaitForPendingFinalizers();
        }

        static long GetMemoryUsage()
        {
            using var proc = Process.GetCurrentProcess();
            // 改用WorkingSet64获取物理内存(工作集)占用,PrivateMemorySize64是提交内存大小
            return proc.WorkingSet64;
        }

        private enum ConsumptionStrategy
        {
            AllocHGlobal,
            ByteArray
        }
    }
}

修改后运行程序,即可看到物理内存占用达到预期值,AWS平台也能正常识别到内存增长触发扩容逻辑。

内容的提问来源于stack exchange,提问作者Stephen Oberauer

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.25 04:06:09