If your web application is crashing with OutOfMemoryException, check Event Viewer for more details. In the stack trace, you should see which function is throwing this exception. In my case, a variable in StringBuilder
type was the root cause.
Solution for OutOfMemoryException related to StringBuilder
I would recommend checking the Private Memory Limit first. Make sure there is no limit or the limit is high enough for the web application to function.
In order to check this feature, go to “Advanced Settings” of your application pool:
If IIS settings look good, it’s time to dive deep in your code. Here are three main causes of OutOfMemoryException
related to StringBuilder (Reference):
MaxCapacity
for theStringBuilder
is reached
The application is attempting to expand aStringBuilder
object beyond the length defined by itsStringBuilder.MaxCapacity
property.- The application is repeatedly concatenating large strings
String concatenation can lead to a large number of memory allocations and memory fragmentation, poor performance, andOutOfMemoryException
exceptions. - The application is trying to assign with a very large set of data to a string
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, anOutOfMemoryException
exception results.
If it is still not clear what the root cause is and you want to find out more information about the issue, use DebugDiag to collect a dump. DebugDiag can be set up to collect crash log, performance log, or memory leak log. In this case, I would recommend collecting crash log as the application is crashing with “out of memory” error.
Note: DebugDiag itself may cause performance issue in the server. It is recommended to run it for a specific period time instead of keeping it running indefinetely.
Are you receiving UnauthorizedAccessException while trying to access a file? Check this post out: (Solved) System.UnauthorizedAccessException occurred in mscorlib.dll