我有一個程序,它獲取的HTML代碼〜500的網頁,每5分鐘獲取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;
}
}
}
和Web客戶端類
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
@Legends在輸出 – mojtaba357
中有很多「線程異常終止」,你可以在你的catch塊中使用'Continue',參考這個鏈接:http://stackoverflow.com/questions/654113/how-do-i-skip-an -iteration對的一-的foreach環 –