How to limit memory allocation

Congrats, you just upgrade you application from x86 to x64.

Now is less probably to have an OutOfMemoryException but you may have now another problem: use all the available memory with possible impact on other processes that are running on the system or on other users that are using your application.

In this post I want to show you one option to limit the process to a certain quantity of RAM: JobObjects

A job object allows groups of processes to be managed as one unit, but in our case we are only attaching one, our target process. It is possible to attach the current process to a job object, but any process can be attached to it (a process you started or identify one by its name).

I invite you to check the sample source code (c#) that can be found here.

It is important to set the BasicLimitInformation.LimitFlags to JOB_OBJECT_LIMIT_PROCESS_MEMORY(0x00000100) otherwise this will not work.

Conclusions: There are situation when you want to set a maximum limit of how much memory your application can allocate e.g. a background service that shouldn’t overload the system. This should be used with caution and if your x64 application is using all the available memory this may be a sign of a memory leak.

JobObjects represents a quick way to set this up. For more complex allocation problems you may consider to implement a custom CLR Host where you can not only limit the memory allocation but you can also control how is allocated.

Leave a Reply

Your email address will not be published. Required fields are marked *