有时候,让一个应用程序陷入糟糕的境地,看看它是如何响应的,是很有帮助的。像拔掉网络电缆或移除电源这样的事情会告诉我,我的应用程序有多有弹性,我在哪里有工作要做。
为此,我试图找出在.Net中强制使用.Net的最快方法。在简单的控制台应用程序中执行此操作将允许我将此场景注入正在运行的应用程序中。显然,在处理OutOfMemoryExceptions时还需要考虑其他事情(例如内存碎片和垃圾收集器如何分配不同的代),但这对本实验的范围并不重要。
更新
为了澄清问题的目的,重要的是要注意的是,简单地抛出内存异常是没有帮助的,因为我想看看当内存压力增加时,程序将如何反应。本质上,我希望将GC刺激到一个积极的收集模式,并监视它对性能的影响,直到进程因内存不足异常而死亡。
发布于 2016-08-19 18:53:07
举个例子来自MSDN。
下面的示例说明了当示例尝试插入将导致对象的长度属性超过其最大容量的字符串时,调用StringBuilder.Insert(Int32, string, Int32 32)方法引发的Int32异常
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.此外,它还说明了如何纠正错误。
将对StringBuilder.StringBuilder(Int32, any 32)构造函数的调用替换为调用任何其他StringBuilder构造函数重载。StringBuilder对象的最大容量将设置为其默认值,即Int32.MaxValue。 调用StringBuilder.StringBuilder(Int32, any 32)构造函数,该构造函数的maxCapacity值足够大,足以容纳对StringBuilder对象的任何扩展。
发布于 2016-08-19 18:52:46
根据MSDN
OutOfMemoryException异常有两个主要原因:
在我看来,第一次使用字符串生成器会更容易一些。
这样做是可行的:
var sb = new StringBuilder(5, 5);
sb.Insert(0, "hello", 2);https://stackoverflow.com/questions/39045936
复制相似问题