我正在管理一个大型项目,需要以 xml 格式序列化和发送对象。该对象约为 130 mb。
(注意:我没有写这个项目,所以在这个方法之外进行编辑,或者彻底改变架构不是一个选项。它正常工作得很好,但是当对象这么大时,它会抛出内存异常。我需要以另一种方式处理大型对象。)
当前代码是这样的:
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() 处抛出内存不足异常。
我重写了它以使用我更喜欢的“使用”块:
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,所以我不确定为什么会出现内存不足错误)。