0

我正在管理一个大型项目,需要以 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,所以我不确定为什么会出现内存不足错误)。

4

1 回答 1

0

好吧,我发现最好的解决方案是直接序列化到文件,然后传递文件而不是传递字符串:

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();
                }
            }
        }
    }
}

当然,现在我还有另一个问题要发布……那就是反序列化文件!

于 2016-10-17T23:10:27.740 回答