|
|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
Announcements
Services
Chapters
Feature Zones
|
Note: This is an unedited contribution. If this article is inappropriate,
needs attention or copies someone else's work without reference then please
Report This Article
IntroductionIt 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. ApproachWindows 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:
This code is demonstrated in the PublicDomain package in the method PublicDomain.Win32.Job.CreateJobWithMemoryLimits(uint minWorkingSetSize, uint maxWorkingSetSize, params Process[] processesToLimit), which 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: 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
}
}
PublicDomainThe 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.
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||