c# - 如何克服从 API 中提取大型 xml 文档的 OutOfMemoryException?

标签 c# .net out-of-memory

我正在从 API 中提取超过 100 万条记录。拉动工作正常,但在尝试将 ReadToEnd 放入字符串变量时出现内存不足异常。

代码如下:

        XDocument xmlDoc = new XDocument();

        HttpWebRequest client = (HttpWebRequest)WebRequest.Create(uri);
        client.Timeout = 2100000;//35 minutes
        WebResponse apiResponse = client.GetResponse();

        Stream receivedStream = apiResponse.GetResponseStream();
        StreamReader reader = new StreamReader(receivedStream);

        string s = reader.ReadToEnd();

堆栈跟踪:

at System.Text.StringBuilder.ToString()
at System.IO.StreamReader.ReadToEnd()
at MyApplication.DataBuilder.getDataFromAPICall(String uri) in
    c:\Users\RDESLONDE\Documents\Projects\MyApplication\MyApplication\DataBuilder.cs:line 578
at MyApplication.DataBuilder.GetDataFromAPIAsXDoc(String uri) in
c:\Users\RDESLONDE\Documents\Projects\MyApplication\MyApplication\DataBuilder.cs:line 543

我该怎么做才能解决这个问题?

最佳答案

听起来您的文件对于您的环境来说太大了。为大文件加载 DOM 可能会出现问题,尤其是在使用 win32 平台时(您尚未说明是否属于这种情况)。

您可以将 XmlReader 的速度和内存效率与 XElement/Xnode 等的便利性结合起来,并使用 XStreamingElement 来保存处理后的转换内容。这对于大文件来说内存效率更高

这是一个伪代码示例:

    // use a XStreamingElement for writing
    var st = new XStreamingElement("root"); 
    using(var xr = new XmlTextReader(stream))
    {
        while (xr.Read())
        {
            // whatever you're interested in
            if (xr.NodeType == XmlNodeType.Element) 
            {
                var node = XNode.ReadFrom(xr) as XElement;
                if (node != null)
                {
                    ProcessNode(node);
                    st.Add(node);
                }
            }

        }
    }
    st.Save(outstream); // or st.WriteTo(xmlwriter);

关于c# - 如何克服从 API 中提取大型 xml 文档的 OutOfMemoryException?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13710337/

相关文章:

php - Apache httpd 使用所有内存直到服务器关闭

c# - Bot Framework Composer - 读取应用程序设置

c# - 从 C# 中的 JsonResult 中删除一个元素

.net - .Net Concurrent BlockingCollection 有内存泄漏吗?

android - 在 Android 中解析 5MB JSON 响应时出现内存不足异常

python - Python 中两个(非传统)向量的欧氏距离

c# - PowerShell 在 NavigateComplete2 事件触发时崩溃

c# - 如何在 Open XML SDK 中有效地缓冲和刷新流

c# - 如何查找单元格的命名范围 - VSTO

c# - 在 Visual Studio 代码分析中使用 CustomDictionary.xml 进行花式标识符