以下是.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)您捕获到此异常并对其调用.ToString
3)ToString()
尝试将内存分配给堆栈跟踪,但是...没有内存,并且另一个OutOfMemoryException
上升。
在注释中,您说过XML文档有几百KB,如果您的服务器以32位运行,则这可能是一个问题,因为LOH碎片化了。
关于c# - Exception.ToString()上的OutOfMemory异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12094841/