在 .NET Core 中,如何增加正在使用的物理内存?

In .NET Core, how can I increase the physical memory in use?

为了测试容器的自动缩放,我想将正在使用的物理内存设置为特定级别。听起来很简单,但是我 运行 的代码只设置了提交,而不是使用的物理内存。 AWS 也没有看到内存增加。

我尝试了两种策略,使用 Marshal.AllocHGlobal,以及新的 byte[...].

这是 运行 之前的内存使用情况:

这是 运行(使用 5,000MB)时的样子:

如您所见,dotnet.exe 进程提交了 5GB,但物理内存没有增加。

从应用程序输出 PrivateMemorySize64 显示:

Before:   9027584 
After: 5245612032

这是我正在使用的代码:

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($"Memory consumption = {GetMemoryUsage()}");

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

            const int ONE_MEGABYTE = 1024 * 1024;

            long minBytesToUse = ONE_MEGABYTE * (long)MIN_MB_TO_USE;

            while (GetMemoryUsage() < minBytesToUse)
            {
                switch (strategy)
                {
                    case ConsumptionStrategy.ByteArray: usedMemory.Add(new byte[ONE_MEGABYTE * 10]); break;
                    case ConsumptionStrategy.AllocHGlobal: memoryPointers.Add(Marshal.AllocHGlobal(ONE_MEGABYTE * 10)); break;
                }
            }

            Console.WriteLine($"Memory consumption = {GetMemoryUsage()}");
            Console.WriteLine($"Seconds to allocate memory: {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();
            return proc.PrivateMemorySize64;
        }

        private enum ConsumptionStrategy
        {
            AllocHGlobal,
            ByteArray
        }
    }
}

我发现我必须实际使用已分配的 RAM。我设法通过为每 512 个字节设置一个值来做到这一点:

private static void CreateByteArray()
{
    var bytes = new byte[ONE_MEGABYTE * 10];
    _usedMemory.Add(bytes);
    for (var i = 0; i < ONE_MEGABYTE * 10; i += 512)
    {
        bytes[i] = 255;
    }
}