How to get an OutOfMemoryException in .Net

It is sometimes useful to get the application in a bad situation to see how it reacts. Things like disconnecting a network cable or turning off the power will show me how stable my application is and where I should work.

To this end, I am trying to figure out what is the fastest way to force OutOfMemoryExceptionin .Net. Running this in a simple console application will allow me to include this script in a running application. Obviously, there are other things to consider when working with OutOfMemoryExceptions(for example, memory fragmentation and how the garbage collector allocated different generations), but this is not important for the volume of this experiment.

Update
To clarify the purpose of the question, it is important to note that a simple memory exception is not useful, since I want to see how the program will respond when the memory pressure increases. In essence, I want to stimulate the GC into an aggressive collection mode and monitor how this affects performance until the process disappears due to an exception from memory.

+4
source share
2 answers

One example from MSDN .

The following example illustrates an OutOfMemoryException exception caused by a call to the StringBuilder.Insert (Int32, String, Int32) method when the example tries to insert a string that causes the Object's Length property to exceed the maximum capacity

using System;
using System.Text;

public class Example
{
   public static void Main()
   {
      StringBuilder sb = new StringBuilder(15, 15);
      sb.Append("Substring #1 ");
      try {
         sb.Insert(0, "Substring #2 ", 1);
      }
      catch (OutOfMemoryException e) {
         Console.WriteLine("Out of Memory: {0}", e.Message);
      }
   }
}
// The example displays the following output:
//    Out of Memory: Insufficient memory to continue the execution of the program.

Further, it says how to fix the error.

StringBuilder.StringBuilder(Int32, Int32) StringBuilder. StringBuilder , Int32.MaxValue.

StringBuilder.StringBuilder(Int32, Int32) maxCapacity, StringBuilder.

+4

MSDN:

OutOfMemoryException :

  • StringBuilder , StringBuilder.MaxCapacity.

  • . , . OutOfMemoryException, . " ", .

    OutOfMemoryException . , catch, . FailFast , .

, .

:

var sb = new StringBuilder(5, 5);
sb.Insert(0, "hello", 2);
+2

Source: https://habr.com/ru/post/1651831/


All Articles