Tuesday, 23 March 2010

Setting Physical Memory Limit for a .NET application

We needed to limit the physical memory used by a .NET application as it was taking too much of it and the other apps appeared to be in a struggle mode.

The straightforward way appeared to use Process.GetCurrentProcess().MaxWorkingSet. Strangely, no matter what we tried, this never worked. Yet to figure out why it does not work - if anyone has a clue, please ping.

Anyways, looking at options we came across job objects in Windows that allow setting the max working set. So the approach that finally worked was this:

1.) Create a Job object using CreateJobObject() Win32 call

2.) Setup the memory limits against this job using

3.) Assign our process to this job using AssignProcessToJob().

Now, when we look at the task manager, the physical memory assigned to this process never goes over the specified limit. All good.

Note that this is applicable only for the physical memory and not for the virtual memory - no limits can be set for this [?]. The physical memory limit is affected when the application is paged-in from the page file into the memory.

No comments: