使用 MaxWorkingSet 限制进程内存 [英] Limiting process memory with MaxWorkingSet

查看:35
本文介绍了使用 MaxWorkingSet 限制进程内存的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

MSDN:

public IntPtr MaxWorkingSet { get;放;}

获取或设置允许的最大值相关联的工作集大小过程.财产价值:最高允许的工作集大小进程的内存,以字节为单位.

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..

一些代码:

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)
        {

        }
    }
}

在达到 2mb 的限制后,我期待 OutOfMemory 异常,但没有任何反应.如果我打开任务管理器,我可以看到我的应用程序使用的内存量在没有任何限制的情况下不断增长.

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

推荐答案

不,这不会限制进程使用的内存量.它只是围绕 SetProcessWorkingSetSize 的一个包装器,a) 是一个推荐值,b) 限制了进程的 working set,也就是 物理量> 此进程可以消耗的内存 (RAM).

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.

它绝对不会不会在该进程中导致内存不足异常,即使它分配的内容明显多于您设置的 MaxWorkingSet 属性.

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.

对于您尝试执行的操作,还有一种替代方法——Win32 作业对象 API.Codeplex (http://jobobjectwrapper.codeplex.com/) 上有一个托管包装器,我对此做出了贡献.它允许您创建一个进程并限制该进程可以使用的内存量.

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.

这篇关于使用 MaxWorkingSet 限制进程内存的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆