m_beta
m_beta

Reputation: 162

MemoryStream object throwing System.OutOfMemoryException

I've this piece of code which works fine in my machine but throws System.OutOfMemoryException in another machine. I'm just trying to initialize MemoryStream object and then write the contents of xDoc in it. xDoc is an object of datatype XDocument and in my machine I can see that the length of stream when written with the contents of xDoc is 58070847.

MemoryStream stream = new MemoryStream();
xDoc.Save(stream);
stream.Position = 0;
using (var sr = new StreamReader(stream))
{
    strXml = sr.ReadToEnd();
}

There are several questions for System.OutOfMemoryException here but they don't answer my problem.

Things that I tried :

None of the above worked but strangely the below piece of code works and I wonder how.

MemoryStream stream = new MemoryStream();
MessageBox.Show("Loading data"); //Added this for reference while testing and strangely doesn't throw any error!!
xDoc.Save(stream);
stream.Position = 0;
using (var sr = new StreamReader(stream))
{
    strXml = sr.ReadToEnd();
}

I wish to understand why adding a MessageBox statement works

Thanks

Upvotes: 0

Views: 397

Answers (1)

GazTheDestroyer
GazTheDestroyer

Reputation: 21241

You're using large, contiguous amounts of memory to hold a serialised xml document in memory. There's no need for this. xDoc can serialise straight to/from disk, and will hold a much smaller binary representation.

The probable reason that ToString() works whereas Save() doesn't, is because MemoryStream will double its buffer each time the stream passes the end of buffer. So it's not just one 60MB contiguous memory block you're reserving, it's multiple blocks that double in size each time up to 60MB. These will be on the large object heap that does not get compacted in the same way the normal heap.

Upvotes: 1

Related Questions