我想写一小段程序启动线程,以线性方式消耗可用的RAM内存,直到某个级别,并停止(理想情况下,暂停直到"足够"的内存被释放并继续创建线程之后,等等上.)
我尝试了以下,但list.Add(new byte[])需要连续的RAM空间并丢弃OutOfMemoryException,这不是我想要模拟的.
编辑:
我有一个多线程内存饥饿的应用程序,吃了一大堆RAM GB.我想要的是在"实验室条件"中隔离/重现这种情况来解决它,即编写自适应mem监视/线程限制器草案.我正在使用x64 OS和x64平台.为了说清楚:我想看到的结果是任务管理器内存监视器由于程序而直接上升.
static void Main(string[] args)
{
ComputerInfo ci = new ComputerInfo();
D("TOTAL PHYSICAL MEMORY : " + Math.Round(ci.TotalPhysicalMemory / Math.Pow(10,9),3) +" GB");
//########### Fill Memory ###############
var list = new List<byte[]>();
Thread FillMem= new Thread(delegate()
{
while (Process.GetCurrentProcess().PrivateMemorySize64 < MAX_MEM_LEVEL)
{
list.Add(new byte[1024 * 10000]); //<- I Need to change this
Thread.Sleep(100);
}
});
FillMem.Start();
//########### Show used Memory ###############
Thread MonitorMem = new Thread(delegate()
{
while (true)
{
D("PROCESS MEMORY : " + Math.Round(Process.GetCurrentProcess().PrivateMemorySize64 / Math.Pow(10, 6), 3) + " MB");
Thread.Sleep(1000);
}
});
MonitorMem.Start();
Console.Read();
}
Run Code Online (Sandbox Code Playgroud)
这个问题仍然令人困惑; 我不清楚你在这里想做什么以及为什么.
如果你真的想要消耗物理内存 - 也就是说,告诉操作系统没有,真的不使用机器中安装的物理RAM芯片的这一部分用于我所说的以外的任何东西 - 那么我可能会使用来自非托管代码的恰当命名的AllocateUserPhysicalPages函数.
这将减少可用于其他用途的物理内存量,从而迫使更多虚拟内存页面转到页面文件.
除了使你机器上运行的所有程序慢得多之外,我不确定你打算通过这个来实现什么.你能澄清一下吗?