Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does .NET framework allocate memory for OutOfMemoryException?

People also ask

What causes system OutOfMemoryException?

When data structures or data sets that reside in memory become so large that the common language runtime is unable to allocate enough contiguous memory for them, an OutOfMemoryException exception results.

Which exception type occurs in C# when a program does not get enough memory to execute the code?

OutOfMemoryException in C# is an exception that is thrown by the . NET framework execution engine when the program does not have enough memory to continue its execution.

How do you avoid OutOfMemoryException?

Well, according to the topic of the question, best way to avoid out of memory exception would be not to create objects that fill in that memory. Then you can calculate the length of your queue based on estimate of one object memory capacity. Another way would be to check for memory size in each worker thread.

How do you resolve system OutOfMemoryException was thrown?

OutOfMemoryException' was thrown. To resolve this issue, I had to restart Visual Studio or go to the Windows Task Manager and terminate IIS Express process. This error could happen due to a variety of reasons related to memory consumption of the application.


It is preallocated by the runtime. If you explore the heap of any managed process you'll find an instance of that exception.

Here are the preallocated exceptions of a Hello World app:

0:003> !dumpheap -stat -type Exception
Statistics:
      MT    Count    TotalSize Class Name
735f2920        1           84 System.ExecutionEngineException
735f28dc        1           84 System.StackOverflowException
735f2898        1           84 System.OutOfMemoryException
735f2744        1           84 System.Exception
735f2964        2          168 System.Threading.ThreadAbortException

When an out-of-memory condition is encountered inside the runtime, it calls ThrowOutOfMemory. This calls Exception::GetOOMException, which constructs the object on the stack and then copies it to a statically-allocated global instance, which is then thrown.

This is not the managed Exception, though, it a C++ exception declared in ex.h. C++ Exceptions are converted to managed Exceptions in clrex.cpp, which contains code to specifically throw the preallocated managed OutOfMemoryException, which was originally allocated and constructed in appdomain.cpp.

Note: Some of these source files are large and may hang your browser for several seconds while it loads the syntax highlighting.

The call sites that Tim Schmelter linked in a comment on the other answer aren't related to the runtime running out of memory and being unable to construct an object.