c#序列化xmlwriter stringwriter大对象内存不足帮助
本文关键字:对象 内存不足 帮助 stringwriter 序列化 xmlwriter | 更新日期: 2023-09-27 18:13:14
我正在管理一个大型项目,需要序列化和发送xml格式的对象。
(注意:我没有写这个项目,所以在这个方法之外进行编辑,或者彻底改变架构不是一个选择。它通常工作得很好,但当对象这么大时,它会抛出内存异常。我需要用另一种方法来处理大对象
当前代码是:
public static string Serialize(object obj)
{
string returnValue = null;
if (null != obj)
{
System.Runtime.Serialization.DataContractSerializer formatter = new System.Runtime.Serialization.DataContractSerializer(obj.GetType());
XDocument document = new XDocument();
System.IO.StringWriter writer = new System.IO.StringWriter();
System.Xml.XmlTextWriter xmlWriter = new XmlTextWriter(writer);
formatter.WriteObject(xmlWriter, obj);
xmlWriter.Close();
returnValue = writer.ToString();
}
return returnValue;
}
在returnValue = writer.ToString()处抛出内存不足异常。
我重写了它,使用我喜欢的"using"块:
public static string Serialize(object obj)
{
string returnValue = null;
if (null != obj)
{
System.Runtime.Serialization.DataContractSerializer formatter = new System.Runtime.Serialization.DataContractSerializer(obj.GetType());
using (System.IO.StringWriter writer = new System.IO.StringWriter())
{
using (System.Xml.XmlTextWriter xmlWriter = new XmlTextWriter(writer))
{
formatter.WriteObject(xmlWriter, obj);
returnValue = writer.ToString();
}
}
}
return returnValue;
}
研究这一点,似乎StringWriter上的ToString方法实际上使用了两倍的RAM。(我实际上有足够的RAM自由,超过4 gb,所以不确定为什么我得到内存不足的错误)。
嗯,我发现最好的解决方案是直接序列化到一个文件,然后不是传递字符串,而是传递文件:
public static void Serialize(object obj, FileInfo destination)
{
if (null != obj)
{
using (TextWriter writer = new StreamWriter(destination.FullName, false))
{
XmlTextWriter xmlWriter = null;
try
{
xmlWriter = new XmlTextWriter(writer);
DataContractSerializer formatter = new DataContractSerializer(obj.GetType());
formatter.WriteObject(xmlWriter, obj);
}
finally
{
if (xmlWriter != null)
{
xmlWriter.Flush();
xmlWriter.Close();
}
}
}
}
}
当然,现在我有另一个问题,我将发布…这就是对文件进行反序列化!