Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Limiting process memory with MaxWorkingSet

MSDN:

public IntPtr MaxWorkingSet { get; set; }

Gets or sets the maximum allowable working set size for the associated process. Property Value: The maximum working set size that is allowed in memory for the process, in bytes.

So, as far as I understand, I can limit amount of memory that can be used by a process. I've tried this, but with no luck..

Some code:

public class A
{
    public void Do()
    {
        List<string> guids = new List<string>();
        do
        {
            guids.Add(Guid.NewGuid().ToString());
            Thread.Sleep(5);
        } while (true);
    }
}


public static class App
{
    public static void Main()
    {
        Process.GetCurrentProcess().MaxWorkingSet = new IntPtr(2097152);
        try
        {
            new A().Do();
        }
        catch (Exception e)
        {

        }
    }
}

I'm expecting OutOfMemory exception after the limit of 2mb is reached, but nothing happens.. If I open Task Manager I can see that the amount of memory my application uses is growing continiously without any limits.

What am I doing wrong? Thanks in advance

like image 830
Andrey Avatar asked Jan 31 '11 14:01

Andrey


People also ask

What is the maximum size of process address space?

The address space of a process is divided into two parts, User space: On standard 32 bit x86_64 architecture,the maximum addressable memory is 4GB , out of which addresses from 0x00000000 to 0xbfffffff = (3GB) meant for code, data segments.


1 Answers

No, this doesn't limit the amount of memory used by the process. It's simply a wrapper around SetProcessWorkingSetSize which a) is a recommendation, and b) limits the working set of the process, which is the amount of physical memory (RAM) this process can consume.

It will absolutely not cause an out of memory exception in that process, even if it allocates significantly more than what you set the MaxWorkingSet property to.

There is an alternative to what you're trying to do -- the Win32 Job Object API. There's a managed wrapper for that on Codeplex (http://jobobjectwrapper.codeplex.com/) to which I contributed. It allows you to create a process and limit the amount of memory this process can use.

like image 147
Sasha Goldshtein Avatar answered Sep 23 '22 02:09

Sasha Goldshtein