即使有 30 GB 内存可用,也会出现内存不足异常

Abh*_*dav 6 .net c# memory memory-management windows-server-2008

我有一个程序(x64)消耗大量内存。我正在运行win server 2008 R2 SP148 GB RAM(64 bit).net frame work 4.5.

我也在gcAllowVeryLargeObjects = trueapp.config中设置了。

当我运行该程序时,它消耗了 18 GB 内存,之后出现异常

EXCEPTION: System.OutOfMemoryException: Insufficient memory to continue the execution of the program.

   at System.Text.StringBuilder.ExpandByABlock(Int32 minBlockCharCount)
   at System.Text.StringBuilder.Append(Char* value, Int32 valueCount)
   at System.Text.StringBuilder.Append(String value)
   at System.Xml.XmlTextEncoder.Write(String text)
   at System.Xml.XmlTextWriter.WriteWhitespace(String ws)
   at System.Xml.XmlElement.WriteElementTo(XmlWriter writer, XmlElement e)
   at System.Xml.XmlNode.get_OuterXml()
   at System.Security.Cryptography.Xml.Utils.PreProcessElementInput(XmlElement e
   lem, XmlResolver xmlResolver, String baseUri)
   at System.Security.Cryptography.Xml.Reference.CalculateHashValue(XmlDocument
   document, CanonicalXmlNodeList refList)
   at System.Security.Cryptography.Xml.SignedXml.BuildDigestedReferences()
   at System.Security.Cryptography.Xml.SignedXml.ComputeSignature()
Run Code Online (Sandbox Code Playgroud)

它给出了“内存不足”,但我们仍然有 30 GB 可用内存。是 .net 应用程序的限制还是服务器的限制给了我这个错误。

Han*_*ant 7

您遇到了 StringBuilder 类的内部限制,它无法生成包含多个int.MaxValue字符的字符串。这一限制在 .NET 中是相当严格的,gcAllowVeryLargeObjects 可以提供帮助,但不能解决它。核心问题是int类型不够大,无法再索引字符串。

您必须编写更智能的代码来解决这个问题。这需要从使用 StreamWriter 而不是 StringWriter 开始。换句话说,写入文件而不是内存。

您仍然可以使用计算机上的所有 RAM,文件首先写入文件系统缓存。你的程序不会变慢。


Tig*_*ran 0

我想到了一件事,即使问题中没有明确的证据。

请记住,集合BCL存在内存限制List<T>,无论是32位还是64位。在两种架构上,单个集合实例可以分配的最大内存量不超过。2GB

您可以查看您的类型的使用情况,特别是List<T>,是否发生了泄漏。

希望这可以帮助。