4

So I want to test my windows application under low memory conditions, and I have found that the easiest way to do this is to create another app (a Console application) that just hogs memory.

I have created this monster:

while (true)
{
    try
    {
        Marshal.AllocHGlobal(1024);
    }
    catch{}
}

But it only goes to 3.7 GB. I then open another instance of this application and it goes back down.

How can I keep the garbage collector from collecting my allocations?

Or: how can I test low-memory conditions on my universal windows application?

Nasreddine
  • 36,610
  • 17
  • 75
  • 94
vrwim
  • 13,020
  • 13
  • 63
  • 118
  • Do you have to write your own app, there are a few freeware ones out there on there. e.g. [TestLimit](https://live.sysinternals.com/WindowsInternals/) - blog on [how to use](https://blogs.msdn.microsoft.com/vijaysk/2012/10/26/tools-to-simulate-cpu-memory-disk-load/) – DaveShaw May 31 '16 at 20:52
  • 2
    Have you checked out [How can I simulate a low memory condition in Windows 7](http://stackoverflow.com/questions/7827716/how-can-i-simulate-a-low-memory-condition-in-windows-7) or [Tools To Simulate CPU / Memory / Disk Load](https://blogs.msdn.microsoft.com/vijaysk/2012/10/26/tools-to-simulate-cpu-memory-disk-load/)? – Solarflare May 31 '16 at 20:52
  • Have you tried just yanking memory DIMMS from your machine? Leave it with the minimum necessary to run the OS. – NotMe May 31 '16 at 20:53
  • @NotMe I only have 2 DIMMs, but it is an interesting idea. – vrwim May 31 '16 at 20:56
  • This approach can only exhaust virtual memory, not physical memory. That should be fine - though you'll want to check your virtual memory settings first, set a reasonable upper limit - but when you say "it goes back down" you're probably measuring the wrong thing. – Harry Johnston Jun 01 '16 at 00:48

2 Answers2

3

You can try changing the GCSettings latency mode to SustainedLowLatency which will avoid garbage collection at all unless the system will run out.

GCSettings.LatencyMode = GCLatencyMode.SustainedLowLatency;
bodangly
  • 2,473
  • 17
  • 28
1

You are probably running into the limit that you see because you are running your memory hog as a 32-bit process, which can only address ~4GB of memory.

Try running as a 64-bit process (compile for x64 explicitly), or spawning multiple copies.

That said, there are better ways to limit the memory available to the process under test. One example is given here: Set Windows process (or user) memory limit

Community
  • 1
  • 1
Chris Shain
  • 50,833
  • 6
  • 93
  • 125