【发布时间】:2017-01-04 13:33:40
【问题描述】:
我有一个程序每 5 分钟获取约 500 个网页的 html 代码
一直正常运行,直到第一次失败(6秒后无法下载源)
之后所有线程都会失败
如果我重新启动程序,它会再次正常运行,直到...
我哪里错了,我应该怎么做才能做得更好?
此函数每 5 分钟运行一次:
foreach (Company company in companies)
{
string link = company.GetLink();
Thread t = new Thread(() => F(company, link));
t.Start();
if (!t.Join(TimeSpan.FromSeconds(6)))
{
Debug.WriteLine( company.Name + " Fails");
t.Abort();
}
}
这个函数下载html代码
private void F(Company company, string link)
{
try
{
string htmlCode = GetInformationFromWeb.GetHtmlRequest(link);
company.HtmlCode = htmlCode;
}
catch (Exception ex)
{
}
}
还有这个类:
public class GetInformationFromWeb
{
public static string GetHtmlRequest(string url)
{
using (MyWebClient client = new MyWebClient())
{
client.Encoding = Encoding.UTF8;
string htmlCode = client.DownloadString(url);
return htmlCode;
}
}
}
和网络客户端类
public class MyWebClient : WebClient
{
protected override WebRequest GetWebRequest(Uri address)
{
HttpWebRequest request = base.GetWebRequest(address) as HttpWebRequest;
request.AutomaticDecompression = DecompressionMethods.Deflate | DecompressionMethods.GZip;
return request;
}
}
【问题讨论】:
-
返回的异常是什么?
-
@Legends 输出中有很多“线程中止异常”
-
你可以在你的catch块中使用
Continue,参考这个链接:stackoverflow.com/questions/654113/…
标签: c# .net httpwebrequest webrequest httpwebresponse