C# Increase Heap Size - Is It Possible

后端 未结 5 960
离开以前
离开以前 2020-12-07 01:01

I have an out of memory exception using C# when reading in a massive file

I need to change the code but for the time being can I increase the heap size (like I would

5条回答
  •  無奈伤痛
    2020-12-07 01:58

    As others have already pointed out, this is not possible. The .NET runtime handles heap allocations on behalf of the application.

    In my experience .NET applications commonly suffer from OOM when there should be plenty of memory available (or at least, so it appears). The reason for this is usually the use of huge collections such as arrays, List (which uses an array to store its data) or similar.

    The problem is these types will sometimes create peaks in memory use. If these peak requests cannot be honored an OOM exception is throw. E.g. when List needs to increase its capacity it does so by allocating a new array of double the current size and then it copies all the references/values from one array to the other. Similarly operations such as ToArray makes a new copy of the array. I've also seen similar problems on big LINQ operations.

    Each array is stored as contiguous memory, so to avoid OOM the runtime must be able to obtain one big chunk of memory. As the address space of the process may be fragmented due to both DLL loading and general use for the heap, this is not always possible in which case an OOM exception is thrown.

提交回复
热议问题