我正在使用Xsd2Code来序列化我的对象,以便生成一个Xml文件。
它工作得很好,就在文件包含大量数据时,我得到了一个OutOfMemoryException。下面是我用来序列化对象的代码:
/// Serializes current EntityBase object into an XML document
/// </summary>
// <returns>string XML value</returns>
public virtual string Serialize() {
System.IO.StreamReader streamReader = null;
System.IO.MemoryStream memoryStream = null;
try {
memoryStream = new System.IO.MemoryStream();
Serializer.Serialize(memoryStream, this);
memoryStream.Seek(0, System.IO.SeekOrigin.Begin);
streamReader = new System.IO.StreamReader(memoryStream);
return streamReader.ReadToEnd();
}
finally {
if (streamReader != null) {
streamReader.Dispose();
}
if (memoryStream != null) {
memoryStream.Dispose();
}
}
}我在这里的要求是,如何扩展内存缓冲区,或者如何避免这样的异常?
致以问候。
发布于 2015-04-07 20:41:20
您没有显示OutOfMemoryException的完整OutOfMemoryException输出,因此很难确定这会有多大帮助,但有一种可能是直接写入StringWriter而不创建中间MemoryStream,如下所示:
public virtual string Serialize()
{
return this.Serialize(Serializer);
}使用扩展方法:
public static class XmlSerializerExtensions
{
class NullEncodingStringWriter : StringWriter
{
public override Encoding Encoding { get { return null; } }
}
public static string Serialize<T>(this T obj, XmlSerializer serializer = null, bool indent = true)
{
if (serializer == null)
serializer = new XmlSerializer(obj.GetType());
// Precisely emulate the output of http://referencesource.microsoft.com/#System.Xml/System/Xml/Serialization/XmlSerializer.cs,2c706ead96e5c4fb
// - Indent by 2 characters
// - Suppress output of the "encoding" tag.
using (var textWriter = new NullEncodingStringWriter())
{
using (var xmlWriter = new XmlTextWriter(textWriter))
{
if (indent)
{
xmlWriter.Formatting = Formatting.Indented;
xmlWriter.Indentation = 2;
}
serializer.Serialize(xmlWriter, obj);
}
return textWriter.ToString();
}
}
}您还可以考虑通过设置indent = false来消除格式化和缩进以节省更多的字符串内存。
这将在一定程度上减少您的峰值内存占用,因为它完全消除了在内存中与结果字符串同时拥有一个大型MemoryStream的需要。但是,它不会极大地减少峰值内存需求,因为MemoryStream占用的内存将与最终string占用的内存成正比。
除此之外,我只能建议尝试stream directly to your database。
https://stackoverflow.com/questions/29497144
复制相似问题