Search code examples
.netperformancegarbage-collectionheap-memory

Can I (and do I ever want to) set the maximum heap size in .net?


Coming from a java background, one of the things I am used to is telling the JVM what the maximum heap size should be. If the running program tries to swallow more than is allowed, and the garbage collector cannot free any more resources, then OutOfMemoryError is thrown and it all goes bang. So setting the maximum heap size is important in Java.

Does this apply in .net? Can you set the heap size limits? Does the CLR just keep growing its heap until it reaches the machine's physical limits? Or is it not an issue in .net for some subtle reason that my Java blinkers stop me from seeing?


Solution

  • You can't set max heap size in .Net unless you host the CLR yourself in a process.

    Edit: To control the memory allocations of CLR including the max heap size, you need to use the hosting api to host the clr and specifically use the "Memory manager interfaces", some starter info can be found here MSDN Magazine, column CLR Inside Out : CLR Hosting APIs

    Edit: to answer you question, why would you want to control the memory allocation or specifically max heap size, you usually don't want to, but if you're writing an application that is like SQL Server or IIS or some real time application then you'd have a pretty good reason to have control over memory and specifically, avoid paging, otherwise the CLR itself and the OS already do a pretty good job for you, and what is left is to ensure your that application uses minimum resources for things to work well.