Nick
Nick

Reputation: 25799

Impose a Memory Limit on the CLR

I'm trying to test the error handling of my code under limited memory situations.

I'm also keen to see how the performance of my code is affected in low memory situations where perhaps the GC has to run more often.

Is there a way of running a .Net applicataion (or NUnit test-suite) with limited memory? I know with Java you can limit the amount of memory the JVM has access to - is there something similar in .Net?

Upvotes: 3

Views: 1095

Answers (2)

usr
usr

Reputation: 171178

You can enlist your process into a Windows Job Object. You can set memory (and other) limits for the job. This is the cleanest and the only sane way to limit the amount of memory that your process can use.

Upvotes: 1

Hans Passant
Hans Passant

Reputation: 941465

This is not an option in the CLR. Memory is managed very differently, there are at least 10 distinct heaps in a .NET process. A .NET program can use the entire virtual memory space available in a Windows process without restrictions.

The simplest approach is to just allocate the memory when your program starts. You have to be a bit careful, you cannot swallow too much in one gulp, the address space is fragmented due to it containing a mix of code and data at different addresses. Memory is allocated from the holes in between. To put a serious dent into the available address space, you have to allocate at least a gigabyte and that's not possible with a single allocation.

So just use a loop to allocate smaller chunks, say one megabyte at a time:

    private static List<byte[]> Gobble = new List<byte[]>();

    static void Main(string[] args) {
        for (int megabyte = 0; megabyte < 1024; megabyte++) 
           Gobble.Add(new byte[1024 * 1024]);
        // etc..
    }

Note that this is very fast, the allocated address space is just reserved and doesn't occupy any RAM.

Upvotes: 3

Related Questions