Click here to Skip to main content
15,867,568 members
Articles / Programming Languages / C#
Article

How to Set the Maximum Memory a Process can Use at the OS Level

Rate me:
Please Sign up or sign in to vote.
2.63/5 (9 votes)
1 Mar 2007CPOL2 min read 111K   18   20
Describes how to use WIN32 methods, and the concepts of Jobs to set a hard limit on the amount of memory a process can use. Also, provides a C# wrapper around the PInvoke calls.

Introduction

It is not a common requirement, but I ran into a scenario where I needed to set a hard Operating System limit on the maximum amount of memory a process could use. The Process.MaxWorkingSet property is, from what I can gather, merely a suggestion and easily worked-around by the Process.

This article describes the general approach to setting a hard limit to the memory a process can use and provides a link with running code to do so.

Approach

Windows has the concept of Job Objects, allowing management of system resources at an OS level, such as CPU or memory requirements.

To set a hard memory limit, the process is simple:

  1. Create a Job object using CreateJobObject
  2. Use the SetInformationJobObject method to set the various process limits and controls, such as memory
  3. Finally, assign a running process to the Job with AssignProcessToJob and it will automatically be held to the limits of the associated Job.

This code is demonstrated in the PublicDomain package in the following method:

C#
PublicDomain.Win32.Job.CreateJobWithMemoryLimits
    (uint minWorkingSetSize, uint maxWorkingSetSize, params Process[] processesToLimit)

This allows you to pass the min/max memory limits and a list of running Processes to apply the limit to.

You can watch the memory rise in task manager and hit the maximum that you set, subsequently throwing OutOfMemory Exceptions (if the GC can't reclaim enough needed memory).

The code returns a C# Job object which is a light wrapper around the handle returned by the WIN32 CreateJobObject method. The C# class also implements IDisposable, and once the Job is disposed, the memory limits are removed:

C#
using (Process p = new Process())
{
    p.StartInfo = new ProcessStartInfo("myexe.exe");
    p.Start();

    using (PublicDomain.Win32.Job j = PublicDomain.Win32.Job.CreateJobWithMemoryLimits(
        (uint)GlobalConstants.BytesInAMegabyte * 12,
        (uint)GlobalConstants.BytesInAMegabyte * 30,
        p))
    {
        // As long as the Job object j is alive, there
        // will be a memory limit of 30 Mb on the Process p
    }
}

PublicDomain

The PublicDomain package is a completely free, public domain collection of oft-needed code and packages for .NET. There is no license, so the code (or any part of it) may be included even in corporate applications. Public domain code has no authority.

History

  • 1st March, 2007: Initial post

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Web Developer
Italy Italy
http://www.codeplex.com/PublicDomain

Comments and Discussions

 
Questionis this working on windows8 64 bit? Pin
AnandChavali3-May-14 22:01
AnandChavali3-May-14 22:01 
AnswerNot True Pin
rvanchis28-Apr-09 20:35
rvanchis28-Apr-09 20:35 
GeneralRe: Not True Pin
schizoidboy6-May-09 5:23
schizoidboy6-May-09 5:23 
AnswerRe: Not True Pin
rvanchis6-May-09 5:55
rvanchis6-May-09 5:55 
Questionhow to use IDisposable Pin
Oren Rosen20-Apr-09 6:07
Oren Rosen20-Apr-09 6:07 
AnswerRe: how to use IDisposable Pin
schizoidboy20-Apr-09 9:47
schizoidboy20-Apr-09 9:47 
GeneralRe: how to use IDisposable Pin
Oren Rosen20-Apr-09 10:47
Oren Rosen20-Apr-09 10:47 
GeneralRe: how to use IDisposable Pin
schizoidboy20-Apr-09 11:25
schizoidboy20-Apr-09 11:25 
GeneralRe: how to use IDisposable Pin
Oren Rosen20-Apr-09 18:24
Oren Rosen20-Apr-09 18:24 
GeneralRe: how to use IDisposable Pin
schizoidboy21-Apr-09 4:41
schizoidboy21-Apr-09 4:41 
GeneralRe: how to use IDisposable Pin
schizoidboy21-Apr-09 4:43
schizoidboy21-Apr-09 4:43 
GeneralRe: how to use IDisposable Pin
Oren Rosen21-Apr-09 9:11
Oren Rosen21-Apr-09 9:11 
hi. This is exactly what i want to do. thanks for the code and just to make sure i am not mistaking in my writing i attached my code sample based on your reply.
also, i have added an exception to the catch.

the problem now is that when running SetLimits() on the process for the second time, i get and 'access denied' exception.
i am building and running the code using Administrator user.
also, RemoveLimits() wont work.

Appreciate your help and time Smile | :)

Thanks,

Oren

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using PublicDomain;
using System.Diagnostics;

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private Win32.Job m_job;

        public static Win32.Job CreateJobWithMemoryLimits(
            uint minWorkingSetSize,
            uint maxWorkingSetSize,
            params Process[] processesToLimit)
        {
            Win32.Job job = new Win32.Job(StringUtilities.RandomString(10, true));
            job.SetLimitWorkingSetSize(minWorkingSetSize, maxWorkingSetSize);

            foreach (Process p in processesToLimit)
            {
                try
                {
                    job.AssignProcess(p);
                }
                catch (Exception e)
                {
                    MessageBox.Show(e.ToString());
                }
            }
            return job;
        }

        public void RemoveLimits()
        {
            if (m_job != null)
            {
                m_job.Dispose();
                m_job = null;
            }
        }

        public void ChangeLimits()
        {
            RemoveLimits();
            Process[] ProcessList = Process.GetProcessesByName("MYPROCESSES");

            m_job = CreateJobWithMemoryLimits(
                uint.Parse(textBox1.Text) * 1048576,
                uint.Parse(textBox2.Text) * 1048576,
                ProcessList);
        }

        private void BT1Set_Click(object sender, EventArgs e)
        {
            ChangeLimits();
        }

        private void BT3Release_Click(object sender, EventArgs e)
        {
            RemoveLimits();
        }


    }
}

GeneralRe: how to use IDisposable Pin
schizoidboy21-Apr-09 14:25
schizoidboy21-Apr-09 14:25 
GeneralRe: how to use IDisposable Pin
Oren Rosen21-Apr-09 19:35
Oren Rosen21-Apr-09 19:35 
GeneralRe: how to use IDisposable Pin
Oren Rosen22-Apr-09 1:06
Oren Rosen22-Apr-09 1:06 
GeneralAccess is denied Error Pin
craigclark77710-Sep-08 7:33
craigclark77710-Sep-08 7:33 
GeneralRe: Access is denied Error Pin
schizoidboy13-Sep-08 15:06
schizoidboy13-Sep-08 15:06 
QuestionMaximum limit? Pin
Todd Smith1-Mar-07 8:02
Todd Smith1-Mar-07 8:02 
AnswerRe: Maximum limit? Pin
Robert Rohde2-Mar-07 2:22
Robert Rohde2-Mar-07 2:22 
AnswerRe: Maximum limit? Pin
The_Mega_ZZTer15-Nov-07 9:34
The_Mega_ZZTer15-Nov-07 9:34 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.