来自其内部StringBuilder调用的BinaryFormatter.Deserialize的OutOfMemory异常

MrW*_*Wuf 5 c# stringbuilder out-of-memory binaryformatter deserialization

我有一个.NET 4 WCF服务,它向客户端发送一些由客户端反序列化的大对象(~115Mb).对象第一次进入时反序列化很好.但是,所有后续调用都会抛出一个OutOfMemoryException.我已经检查过以确保我所有人IDisposables都被包裹起来using.我查看了与此类似的其他问题,例如BinaryFormatter outofmemory异常反序列化 来自MemoryStream的Deserialize在C#中抛出OutOfMemory异常 .我尝试了一些人们推荐的解决方案,包括使用Simon Hewitt的Optimized Serializer.但是,最后,他仍然依赖于BinaryFormatter反序列化对象.

我抓住了OutOfMemoryException并查看了堆栈跟踪(见下文).跟踪似乎源于StringBuilder类中内存利用率的问题.我读过其他文章,关于如何StringBuilder在需要更多空间时使用(长度*2)算法导致内存问题.

at System.Text.StringBuilder.ToString()    
at System.IO.BinaryReader.ReadString()    
at System.Runtime.Serialization.Formatters.Binary.__BinaryParser.ReadObjectString(BinaryHeaderEnum binaryHeaderEnum)    
at System.Runtime.Serialization.Formatters.Binary.__BinaryParser.Run()    
at System.Runtime.Serialization.Formatters.Binary.ObjectReader.Deserialize(HeaderHandler handler, __BinaryParser serParser, Boolean fCheck, Boolean isCrossAppDomain, IMethodCallMessage methodCallMessage)    
at System.Runtime.Serialization.Formatters.Binary.BinaryFormatter.Deserialize(Stream serializationStream, HeaderHandler handler, Boolean fCheck, Boolean isCrossAppDomain, IMethodCallMessage methodCallMessage)    
at System.Runtime.Serialization.Formatters.Binary.BinaryFormatter.Deserialize(Stream serializationStream)
Run Code Online (Sandbox Code Playgroud)

有没有办法以BinaryFormatter不同的方式工作而不使用StringBuilder或是否有更好的替代方案来BinaryFormatter更好地管理内存?

And*_*ren 1

我不建议对任何大小的东西使用 BinaryFormatter(事实上,如果您不使用 BinaryFormatter,它可能会小很多)。如果它是相当简单的数据(例如表格数据)或具有一些约束(例如没有循环引用等),那么使用简单的二进制编写器滚动您自己的二进制序列化,或者使用一些现成的序列化程序(例如protobuf-netjson.net)更加紧凑并且速度明显更快。