有时,让应用程序陷入困境以查看其响应如何会很有帮助。拔掉网络电缆或断电之类的事情将向我展示我的应用程序的弹性以及我需要做的工作。
为此,我试图找出在 .Net 中强制发生 OutOfMemoryException
的最快方法。在一个简单的控制台应用程序中执行此操作将允许我将此场景注入(inject)到正在运行的应用程序中。处理 OutOfMemoryExceptions 时显然还需要考虑其他事情(例如内存碎片以及垃圾收集器如何分配不同的代),但这对于本实验的范围并不重要。
更新
为了澄清问题的目的,重要的是要注意,简单地抛出内存不足异常是没有帮助的,因为我想看看当内存压力增加时程序将如何 react 。本质上,我想刺激 GC 进入积极的收集模式,并监视这对性能的影响,直到进程因内存不足异常而终止。
最佳答案
一个例子from MSDN ..
The following example illustrates the OutOfMemoryException exception thrown by a call to the StringBuilder.Insert(Int32, String, Int32) method when the example tries to insert a string that would cause the object's Length property to exceed its 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.
此外,它还说明了如何纠正错误。
Replace the call to the StringBuilder.StringBuilder(Int32, Int32) constructor with a call any other StringBuilder constructor overload. The maximum capacity of your StringBuilder object will be set to its default value, which is Int32.MaxValue.
Call the StringBuilder.StringBuilder(Int32, Int32) constructor with a maxCapacity value that is large enough to accommodate any expansions to the StringBuilder object.
关于.net - 如何在 .Net 中强制发生 OutOfMemoryException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39045936/