Take the 2-minute tour ×

I have a Mono for Android application that reads XML files using the .NET XmlDocument class. Each document is about 180K.

After parsing each document and creating my own internal data structures, I leave no references to the XmlDocument instance, so it becomes eligible for garbage collection.

The problem is, though, that it takes 5-6 seconds before that collection happens, and if I load multiple documents within 5-6 seconds, my app crashes out to the OS with no error messages printed, no exceptions thrown, etc. It just says that thread 12 exited (I'm not creating any extra threads, so I don't understand why it's thread 12 either -- XmlDocument's thread?).

If I load document 1, then wait 5 seconds, then load document 2, wait 5 seconds then load document 3, etc., then everything is OK.

In that case, during the 5 second wait, I can see the GC kicking in several times and releasing around 1MB of memory in total across 4-5 cycles (some marked EXPLICIT, some marked CONCURRENT).

I also tried adding a call to xmlDocument.RemoveAll() once I am done as suggested by an article I found. I also added a call to GC.Collect() after that. It helped slightly, but it still crashes, just somewhat less often.

Any idea how to either increase the available memory or get XmlDocument to behave better?

share|improve this question
Could you be not disposing a stream or XmlReader that you are loading the document from, or a stream or XmlWriter that you are saving it with, and hence causing stuff to be added to the finaliser queue, and hence causing more GC promotions? –  Jon Hanna Aug 14 '12 at 21:36
If all else fails, try using XDocument. This is a much nicer API, and just maybe it might work better in this scenario. –  jdv-Jan de Vaan Aug 14 '12 at 21:45
Maybe reuse the XmlDocument instances and simply reload them? –  John Saunders Aug 15 '12 at 1:14
Jon Hanna: I am using the constructor that takes a file path string as an argument, so I am not in control of the stream. –  MindJuice Aug 15 '12 at 20:36
John Saunders: It's possible that might help, although even calling RemoveAll() on the XmlDocument then doing a GC.Collect() didn't help much, so maybe not. I think there is some defect in there still. Perhaps something in how the C# XmlDocument interacts with the Java GC. –  MindJuice Aug 15 '12 at 20:41
add comment

1 Answer

up vote 0 down vote accepted

This is not so much an answer as it is an alternative, but I rewrote my XML parsing code using XmlTextReader and the problem no longer occurs.

Of course XmlTextReader doesn't need to load the whole XML file into memory, which is a huge help to memory usage.

I can load multiple files very quickly one after the other with no crashes now.

The XmlTextReader API was more work to get right, but things seem pretty solid now.

share|improve this answer
add comment

Your Answer


