Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
479 views
in Technique[技术] by (71.8m points)

c# - Why is my new XmlTextReader(stream) reading in many megabytes into memory rather than streaming properly?

I am getting Out of Memory Exceptions when STREAMING in XML into an XmlReader! Looking in a memory profiler we can see that it is calling StringBuilder.Append over and over resulting in tons of 128KB buffers filling all of memory.

That's pretty contrary to "streaming". It shouldn't be loading more than one 4KB buffer.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Reading through the .NET source code, it turns out there's a "v1compat" mode that will indeed read way ahead, defeating the purpose of streaming. So, how do you avoid getting it into that stupid mode?

It turns out that there's a HUGE difference between calling 'new XmlTextReader(stream)' and 'XmlReader.Create(stream)' that Microsoft didn't bother to document... and I could never find in any post anywhere... the former puts it into 'v1compat' mode!!!

Sooo, unless you need your XmlReader to behave exactly like it did in .NET 1.1, including improper streaming behavior, you should NEVER EVER call 'new XmlTextReader(stream)' ... instead use 'XmlReader.Create(stream)' or one of the variants that takes an XmlReaderSettings if you need to try to match the settings XmlTextReader used (if you don't pass an XmlReaderSettings, then at least some of the settings will be different... I am not sure what settings would best match 'new XmlTextReader'... if anybody knows, please add that here!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...