【发布时间】:2012-12-04 19:21:31
【问题描述】:
我正在从 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
我可以做些什么来解决这个问题?
【问题讨论】:
-
你应该显示相关代码。
-
尝试循环使用
reader.ReadLine() + WritetoFile而不是reader.ReadToEnd() -
L.B.我可以将它读入一个字符串并处理成一个 XDocument...还是我必须分解成更小的 XDocument?
-
您可能必须改用
XmlReader:msdn.microsoft.com/en-us/library/system.xml.xmlreader.aspx -
Peacemaker,问题是 API 返回带有我必须编码的字符的 XML(例如:&),因此我必须先将其放入字符串中以对这些字符进行编码。
标签: c# .net out-of-memory