Limiting the size of the managed heap in a C# appl

2020-02-12 09:14发布

问题:

Can I configure my C# application to limit its memory consumption to, say, 200MB? IOW, I don't want to wait for the automatic GC (which seems to allow the heap to grow much more than actually needed by this application).

I know that in Java there's a command line switch you can pass to the JVM that achieves this.. is there an equivalent in C#?

p.s.

I know that I can invoke the GC from code, but that's something I would rather not have to do periodically. I'd rather set it once upon startup somehow and forget it.

回答1:

I am not aware of any such options for the regular CLR. I would imagine that you can control this if you implement your own CLR host.

However, I disagree in your assessment of how the heap grows. The heap grows because your application is allocating and holding on to objects.

There are a couple of things you can do to limit the memory usage. Please see this question for some input: Reducing memory usage of .NET applications?



回答2:

The memory manager lets the host provide an interface through which the CLR will request all memory allocations. It replaces both the Windows® memory APIs and the standard C CLR allocation routines. Moreover, the interface allows the CLR to inform the host of the consequences of failing a particular allocation (for example, failing a memory allocation from a thread holding a lock may have certain reliability consequences). It also permits the host to customize the CLR's response to a failed allocation, ranging from an OutOfMemoryException being thrown all the way up through the process being torn down. The host can also use this manager to recapture memory from the CLR by unloading unused app domains and forcing garbage collection. The memory manager interfaces are listed in

Source and More : http://msdn.microsoft.com/en-us/magazine/cc163567.aspx#S2

Edit :

I actually wouldn't recommend you to manage memory by yourself, because more you get in, more problems you will probably run into, instead CLR does that mission perfectly.

But if you say it's very important for me to handle things on my own, then I can't anything.



回答3:

I haven't tried this out, but you could attempt to call SetProcessWorkingSetSizeEx passing in the right flags to enforce that your process never gets more than so much memory. I don't know if the GC will take this into account and clean up more often, or if you'll just get OutOfMemoryExceptions.