问题描述
在将 XML 中的流传输到 XmlReader 时出现内存不足异常!查看内存分析器,我们可以看到它一遍又一遍地调用 StringBuilder.Append 导致大量 128KB 缓冲区填满所有内存.
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.
这与流媒体"完全相反.它不应该加载超过一个 4KB 的缓冲区.
That's pretty contrary to "streaming". It shouldn't be loading more than one 4KB buffer.
推荐答案
通读 .NET 源代码,发现有一种v1compat"模式确实会提前阅读,从而违背了流式传输的目的.那么,你如何避免进入那种愚蠢的模式?
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?
事实证明,调用new XmlTextReader(stream)"和XmlReader.Create(stream)"之间存在巨大差异,Microsoft 没有费心记录......而且我在任何地方的任何帖子中都找不到... 前者将其置于v1compat"模式!!!
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,除非您需要 XmlReader 的行为与 .NET 1.1 中的完全一样,包括不正确的流媒体行为,否则您永远不要调用 'new XmlTextReader(stream)' ... 而是使用 'XmlReader.Create(stream)' 或采用 XmlReaderSettings 的变体之一,如果您需要尝试匹配 XmlTextReader 使用的设置(如果您不传递 XmlReaderSettings,那么至少某些设置会有所不同......我不确定是什么设置最好匹配'new XmlTextReader'...如果有人知道,请在此处添加!
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!
这篇关于为什么我的新 XmlTextReader(stream) 将许多兆字节读入内存而不是正确流式传输?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!