问题描述
环境C#4.5E516G内存预计序列化后数据大小1G左右这个问题如何解决呢?代码:[List<KeyWords>listKeyWords]try{CommonHelper.CGCollect();stringxml=XmlHelper.XmlSerialize(listKeyWords,Encoding.Default);Mutexm=newMutex();if(!string.IsNullOrEmpty(xml)){DocHelper.writeXC(xml,string.Format("{0}{1}",ConfigurationInfo._KEYWORDSPATH,pathName),FileMode.OpenOrCreate,m);}}publicstaticstringXmlSerialize(objecto,Encodingencoding){using(MemoryStreamstream=newMemoryStream()){XmlSerializeInternal(stream,o,encoding);stream.Position=0;using(StreamReaderreader=newStreamReader(stream,encoding)){returnreader.ReadToEnd();}}}错误信息:System.InvalidOperationException:生成XML文档时出错。--->System.OutOfMemoryException:引发类型为“System.OutOfMemoryException”的异常。在System.IO.MemoryStream.set_Capacity(Int32value)在System.IO.MemoryStream.EnsureCapacity(Int32value)在System.IO.MemoryStream.Write(Byte[]buffer,Int32offset,Int32count)在System.Xml.XmlEncodedRawTextWriter.EncodeChars(Int32startOffset,Int32endOffset,BooleanwriteAllToStream)在System.Xml.XmlEncodedRawTextWriter.FlushBuffer()在System.Xml.XmlEncodedRawTextWriter.RawText(Char*pSrcBegin,Char*pSrcEnd)在System.Xml.XmlEncodedRawTextWriter.RawText(Strings)在System.Xml.XmlEncodedRawTextWriter.WriteStartAttribute(Stringprefix,StringlocalName,Stringns)在System.Xml.XmlEncodedRawTextWriterIndent.WriteStartAttribute(Stringprefix,StringlocalName,Stringns)在System.Xml.XmlWellFormedWriter.WriteStartAttribute(Stringprefix,StringlocalName,StringnamespaceName)在System.Xml.Serialization.XmlSerializationWriter.WriteAttribute(StringlocalName,Stringns,Stringvalue)在Microsoft.Xml.Serialization.GeneratedAssembly.XmlSerializationWriterList1.Write7_WordsareadataModelS(Stringn,Stringns,WordsareadataModelSo,BooleanisNullable,BooleanneedType)在Microsoft.Xml.Serialization.GeneratedAssembly.XmlSerializationWriterList1.Write8_WordsareadataModel(Stringn,Stringns,WordsareadataModelo,BooleanisNullable,BooleanneedType)在Microsoft.Xml.Serialization.GeneratedAssembly.XmlSerializationWriterList1.Write9_KeyWords(Stringn,Stringns,KeyWordso,BooleanisNullable,BooleanneedType)在Microsoft.Xml.Serialization.GeneratedAssembly.XmlSerializationWriterList1.Write10_ArrayOfKeyWords(Objecto)---内部异常堆栈跟踪的结尾---在System.Xml.Serialization.XmlSerializer.Serialize(XmlWriterxmlWriter,Objecto,XmlSerializerNamespacesnamespaces,StringencodingStyle,Stringid)在System.Xml.Serialization.XmlSerializer.Serialize(XmlWriterxmlWriter,Objecto)在Lanwatcher.Tools.XmlHelper.XmlSerializeInternal(Streamstream,Objecto,Encodingencoding)位置
解决方案
本帖最后由 ELVADUAN 于 2015-04-17 16:03:55 编辑
解决方案二:
换个思路就好了,分段操作,分段序列化,分段写入,别让内存太累。。。
解决方案三:
可以使用文件流试试try{XmlSerializerxmlFormat=newXmlSerializer(typeof(List<KeyWords>));using(StreamfStream=newFileStream(serializeFileFullName,FileMode.Create,FileAccess.Write,FileShare.None)){xmlFormat.Serialize(fStream,listKeyWords);}}catch(Exceptione){Trace.WriteLine(e.ToString());}