在多个线程中检查 URL
Checking URLs in multiple Threads
我正在尝试使用以下代码
验证 URL 的列表
class MyClient : WebClient
{
public bool HeadOnly { get; set; }
protected override WebRequest GetWebRequest(Uri address)
{
WebRequest req = base.GetWebRequest(address);
if (HeadOnly && req.Method == "GET")
{
req.Method = "HEAD";
}
return req;
}
}
private static Boolean CheckURL(string url)
{
using (MyClient myclient = new MyClient())
{
try
{
myclient.HeadOnly = true;
// fine, no content downloaded
string s1 = myclient.DownloadString(url);
return true;
}
catch (Exception error)
{
return false;
}
}
}
这很有效,但对于某些网站来说,需要等待一段时间才能获得结果。如何将 URL 列表拆分为 2 个或 4 个部分并使用单独的线程验证每个部分并将进度报告到单个进度条?
请指教
更新:
我正在使用 Backgroundworker
验证 URl
private void URLValidator_DoWork(object sender, DoWorkEventArgs e)
{
foreach (var x in urllist)
{
Boolean valid = CheckURL(x);
}
}
您可以为此使用 Parallel.ForEach
:
using System.Threading.Tasks;
private void URLValidator_DoWork(object sender, DoWorkEventArgs e)
{
Parallel.ForEach(urllist, (url) =>
{
Boolean valid = CheckURL(x);
// Do something with the result or save it to a List/Dictionary or ...
});
}
我正在尝试使用以下代码
验证 URL 的列表class MyClient : WebClient
{
public bool HeadOnly { get; set; }
protected override WebRequest GetWebRequest(Uri address)
{
WebRequest req = base.GetWebRequest(address);
if (HeadOnly && req.Method == "GET")
{
req.Method = "HEAD";
}
return req;
}
}
private static Boolean CheckURL(string url)
{
using (MyClient myclient = new MyClient())
{
try
{
myclient.HeadOnly = true;
// fine, no content downloaded
string s1 = myclient.DownloadString(url);
return true;
}
catch (Exception error)
{
return false;
}
}
}
这很有效,但对于某些网站来说,需要等待一段时间才能获得结果。如何将 URL 列表拆分为 2 个或 4 个部分并使用单独的线程验证每个部分并将进度报告到单个进度条?
请指教
更新:
我正在使用 Backgroundworker
验证 URlprivate void URLValidator_DoWork(object sender, DoWorkEventArgs e)
{
foreach (var x in urllist)
{
Boolean valid = CheckURL(x);
}
}
您可以为此使用 Parallel.ForEach
:
using System.Threading.Tasks;
private void URLValidator_DoWork(object sender, DoWorkEventArgs e)
{
Parallel.ForEach(urllist, (url) =>
{
Boolean valid = CheckURL(x);
// Do something with the result or save it to a List/Dictionary or ...
});
}