Sean U
Sean U

Reputation: 6850

Can I cap a process's RAM usage?

Is it possible to put an artificial limit on the amount of memory a .NET process can use? I'm looking to simulate low-memory situations for testing purposes.

Right now we use a virtual machine for this type of thing. It works, but I'm curious to know if we can figure out a more convenient approach. One that could easily be automated would be ideal.

Edit: As Hans Passant points out, just limiting the amount of virtual memory available to the process won't replace the VM-based tests. The tests are for performance, so I would need to get swapping instead of OutOfMemoryException.

Upvotes: 3

Views: 1259

Answers (3)

Hans Passant
Hans Passant

Reputation: 942408

Right now we use a virtual machine for this type of thing

Which probably means you limited the amount of RAM. That's not much of a test, a Windows process can never run out of RAM. You'll just slow down the process, the operating system will be swapping pages more frequently.

The real limitation is available virtual memory address space. Which is a fixed number for a 32-bit process, 2 gigabytes. Give or take a few non-standard options to increase that number. An OutOfMemoryException tells you that the process doesn't have a hole left in VM big enough to fit the allocation.

You can limit the amount of VM space by simply allocating a bunch of 50 megabyte byte[] arrays and storing them in a static variable of type List<byte[]> at the beginning of Main().

Upvotes: 1

Reed Copsey
Reed Copsey

Reputation: 564891

One that could easily be automated would be ideal.

You can use Windows Job Objects to manage this from code. Processes can be associated with a job, and JOBOBJECT_BASIC_LIMIT_INFORMATION allows you to restrict the working set size.

Alteratively, you can call SetProcessWorkingSetSize on the process directly, which will restrict the maximum allowable memory usage for that process.

Upvotes: 4

Chris Shain
Chris Shain

Reputation: 51369

The windows Application Verifier tool can simulate low resource levels, like low memory: http://msdn.microsoft.com/en-us/library/aa480483.aspx

A more programmatic solution using job objects (as @ReedCopsey also suggests) is here: http://www.codeproject.com/Articles/17831/How-to-Set-the-Maximum-Memory-a-Process-can-Use-at

Upvotes: 2

Related Questions