[英]c# serialization xmlwriter stringwriter out of memory for large objecthelp
我正在管理一个大型项目,需要序列化并以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,因此不确定我为什么会出现内存不足错误)。
好吧,我发现最好的解决方案是直接序列化到文件,然后传递文件而不是传递字符串:
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();
}
}
}
}
}
当然,现在我还有另一个问题要发布...,那就是反序列化文件!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.