.net - 如何在 .Net 中强制发生 OutOfMemoryException

标签 .net

有时,让应用程序陷入困境以查看其响应如何会很有帮助。拔掉网络电缆或断电之类的事情将向我展示我的应用程序的弹性以及我需要做的工作。

为此,我试图找出在 .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/

相关文章:

c# - 如何在 C# 中将 List<BaseClass> 转换为 List<ChildClass>?

.net - 在 WPF 中实例化用户控件时 PresentationFramework.dll 中的 System.IO.IOException

c# - 无法转换为 LINQ to Entities 存储表达式

c# - 为什么这个值不是有效的 DateTime 对象?

用于单元测试的 .net Xml 比较器

.net - 如何解决缺少 SN key 的 ConfuserEx 警告

c# - Java - 通过 Web 服务和 XML 发送可能包含非法字符的 UTF-8 字符串

c# - 是否可以使用 C# 开发 Android 应用程序?

c# - 为一个消费者使用 EasyNetQ 多个处理程序不起作用

c# - 如何使用 TcpListener 和 TcpClient 创建双工连接?