c# - Exception.ToString()上的OutOfMemory异常

标签 c# .net exception exception-handling error-handling

以下是.NET应用程序的一些日志记录输出。

Error in MainFunction.
Message: Exception of type 'System.OutOfMemoryException' was thrown.
InnerException: 
StackTrace:    at System.Text.StringBuilder.ToString()
   at System.Diagnostics.StackTrace.ToString(TraceFormat traceFormat)
   at System.Environment.GetStackTrace(Exception e, Boolean needFileInfo)
   at System.Exception.GetStackTrace(Boolean needFileInfo)
   at System.Exception.ToString(Boolean needFileLineInfo)
   at System.Exception.ToString()
   [the rest of the trace is removed]

对应于以下应用程序代码行。以下是在catch块中,并将字符串返回到实际抛出的方法:
private void MainFunction()
{
   ...

   try
   {
      string doc = CreateXMLDocument(); // <- Out of Memory throws here
   }
   catch (Exception ex)
   {
      CoreLogging("Error in MainFunction.", ex);
   }
}

private string CreateXMLDocument()
{
   try
   {
      //Some basic and well constrained XML document creation:
      ...
   }
   catch (Exception ex)
   {
      return "Exception message: " + ex.ToString();  // <- This is the last line of the trace
   }
}

我该怎么办?显然,应该使用Exception.Message而不是Exception.ToString(),但是我仍然想了解这一点。是否

System.Text.StringBuilder.ToString()上的

  • System.Diagnostics.StackTrace.ToString(TraceFormat traceFormat)上的


  • 意味着CreateXMLDocument中的异常的堆栈跟踪是如此之大导致OutOfMemory?我很好奇这种情况将如何发生,因为CreateXMLDocument中绝对没有循环调用,这是我唯一想到的可能导致大量堆栈跟踪的事情。

    还有其他人遇到过类似情况吗?

  • 最佳答案

    我有点猜测:

    1)CLR引发OutOfMemoryException。 2)您捕获到此异常并对其调用.ToString3)ToString()尝试将内存分配给堆栈跟踪,但是...没有内存,并且另一个OutOfMemoryException上升。

    在注释中,您说过XML文档有几百KB,如果您的服务器以32位运行,则这可能是一个问题,因为LOH碎片化了。

    关于c# - Exception.ToString()上的OutOfMemory异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12094841/

    相关文章:

    C# 和 MongoDB。无法完全保存异常对象

    java - 开发 Android 应用程序时的最佳实践

    java - 继续提示直到满足标准

    c# - 使用 AutoMapper 覆盖已解析的属性类型

    c# - 在 ItemsGrid View 中禁用鼠标滚轮滚动

    c# - 当 View mvc 中的表单中有 foreach 循环时,action 方法的参数应该是什么

    c# - 通过 IP 阻止连接

    c# - 多线程 'fixed'

    c# - 执行计划任务的方法 - Windows/.NET

    android - 尝试读取 csv 文件时出现空指针异常