我正在使用以下代码验证网址
private Boolean CheckURL(string url)
{
using (MyClient myclient = new MyClient())
{
try
{
myclient.HeadOnly = true;
// fine, no content downloaded
string s1 = myclient.DownloadString(url);
statusCode = null;
return true;
}
catch (WebException error)
{
if (error.Response != null)
{
HttpStatusCode scode = ((HttpWebResponse)error.Response).StatusCode;
if (scode != null)
{
statusCode = scode.ToString();
}
}
else
{
statusCode = "Unknown Error";
}
return false;
}
}
}
class MyClient : WebClient
{
public bool HeadOnly { get; set; }
protected override WebRequest GetWebRequest(Uri address)
{
WebRequest req = base.GetWebRequest(address);
// req.Timeout = 3000;
if (HeadOnly && req.Method == "GET")
{
req.Method = "HEAD";
}
return req;
}
}
这适用于大多数情况,但对于某些网址,它会返回误报结果。对于有效URL(当我使用chrome浏览时)方法返回 未找到。此外,对于某些URL,此方法需要花费太多时间来处理。
我做错了什么?请指教..
更新
我正在使用并行检查来自多个主题的网址,这会导致问题吗?
public void StartThreads()
{
Parallel.ForEach(urllist, ProcessUrl);
}
private void ProcessUrl(string url)
{
Boolean valid = CheckURL(url);
this.Invoke((MethodInvoker)delegate()
{
if (valid)
{
//URL is Valid
}
else
{
//URL is Invalid
}
});
}
我正在从BackGround Worker启动线程以防止UI冻结
private void worker_DoWork(object sender, DoWorkEventArgs e)
{
StartThreads();
}