求助:定时循环使用HttpWebRequest访问网页数据,报错未处理的“System.StackOverflowException”类型的异常

qingxin113 2014-06-05 08:13:53
类似网页辅助工具的代码,使用两三个线程定时通过HttpWebRequest访问不同的网页数据获取信息。
运行大概三、四个小时后,报错未处理的“System.StackOverflowException”类型的异常出现在 mscorlib.dll 中。
每次调用也作了垃圾回收,不明白应怎么解决。谢谢
下面是出错的代码:

/// <summary>
/// Web的Get方式
/// </summary>
/// <param name="Url">网址URL</param>
/// <param name="cc">CookieContainer</param>
/// <returns></returns>
public static string GetHtmlMethodForCommon(string Url, ref CookieContainer cc)
{
string strHtmlReturn = "";
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(Url);
//属性配置
webRequest.AllowWriteStreamBuffering = true;
webRequest.Credentials = System.Net.CredentialCache.DefaultCredentials;
webRequest.MaximumResponseHeadersLength = -1;
webRequest.Accept = "image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, application/x-silverlight, application/x-ms-application, application/x-ms-xbap, application/vnd.ms-xpsdocument, application/xaml+xml, application/vnd.ms-excel, application/vnd.ms-powerpoint, application/msword, application/QVOD, application/QVOD, */*";
webRequest.UserAgent = "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; (R1 1.5); .NET CLR 2.0.50727; .NET CLR 3.0.04506.648; .NET CLR 3.5.21022; InfoPath.2; .NET4.0C; .NET4.0E; Alexa Toolbar; u9dnfsh)";
webRequest.ContentType = "application/x-www-form-urlencoded";
webRequest.Method = "GET";

//如果服务器返回错误,他还会继续再去请求,不会使用之前的错误数据,做返回数据
webRequest.ServicePoint.Expect100Continue = false;
webRequest.Timeout = 200000;
ServicePointManager.DefaultConnectionLimit = 50;

webRequest.Headers.Add("Accept-Language", "zh-cn");
webRequest.Headers.Add("Accept-Encoding", "gzip,deflate");
webRequest.KeepAlive = true;
webRequest.CookieContainer = cc;
try
{

//获取服务器返回的资源
//运行三四个小时后,此处报错
using (HttpWebResponse webResponse = (HttpWebResponse)webRequest.GetResponse())
{
if (webResponse.StatusCode == HttpStatusCode.RequestTimeout)//此处作超时响应判断
{
System.Threading.Thread.Sleep(1000);
return null;
}
else
{
Stream responseStream = webResponse.GetResponseStream();
using (StreamReader reader = new StreamReader(webResponse.GetResponseStream(), Encoding.GetEncoding("utf-8")))
{
cc.Add(webResponse.Cookies);
strHtmlReturn = reader.ReadToEnd();
}
}
}
}
catch (WebException ex)
{
strHtmlReturn = "";
throw ex;
}
catch (Exception ex)
{
strHtmlReturn = "";
throw ex;
}
finally
{
webRequest.Abort();
}
return strHtmlReturn;
}
...全文
161 3 打赏 收藏 转发到动态 举报
写回复
用AI写文章
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
qingxin113 2014-06-06
  • 打赏
  • 举报
回复
释放了,运行大概6、7个小时后还是报错。 程序是循环调用,估计还是运行时间长了内存溢出。 用Catch(System.StackOverflowException)捕获算了
anyboy010 2014-06-05
  • 打赏
  • 举报
回复
亲,你这段代码问题多多,主要体现在 资源 释放 方面! webResponse ,responseStream, reader 都是需要释放的啊。 你只是释放了webRequest。
bwangel 2014-06-05
  • 打赏
  • 举报
回复
这段代码没看出问题。 检查一下你的上层代码是否有递归调用。比如一个网站链接很深的话,递归可能栈溢出。

110,549

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • Web++
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧