Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I cap a process's RAM usage?

Tags:

c#

.net

windows

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.

like image 688
Sean U Avatar asked Mar 26 '26 07:03

Sean U


1 Answers

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.

like image 192
Reed Copsey Avatar answered Mar 28 '26 19:03

Reed Copsey