我是线程新手。我试图使用多线程发送HTTP Web请求,我无法实现我需要的东西。 我的要求是向数千个相同或不同的网站发送请求,并解析我从httpwebrequest获得的响应。 在下面的代码中,我发送2个同时线程,我正在寻找10个同时线程。
namespace threading
{
public partial class Form1 : Form
{
delegate string UrlFetcher(string url);
private void button1_Click(object sender, EventArgs e)
{
int i = 1;
UrlFetcher u = new UrlFetcher(Fetch);
UrlFetcher u = new UrlFetcher(Fetch1);
string pageURL = "http://www.google.com";
while (i <= 1000)
{
u.BeginInvoke(pageURL, new AsyncCallback(AfterFetch), "this is state");
i++;
u.BeginInvoke(pageURL, new AsyncCallback(AfterFetch1), "this is state");
i++;
Thread.Sleep(5);
}
}
static string Fetch(string pageURL)
{
HttpWebRequest WebReq = (HttpWebRequest)WebRequest.Create(pageURL);
WebReq.Method = "GET";
HttpWebResponse WebResp = (HttpWebResponse)WebReq.GetResponse();
Stream Answer = WebResp.GetResponseStream();
StreamReader _Answer = new StreamReader(Answer);
string myString = _Answer.ReadToEnd();
return myString;
}
void AfterFetch(IAsyncResult result)
{
string a;
AsyncResult async = (AsyncResult)result;
UrlFetcher fetcher = (UrlFetcher)async.AsyncDelegate;
a = fetcher.EndInvoke(result).ToString();
Regex regx = new Regex(@"<td>([A-Za-z0-9\-]+)\.(com|net)</td>", RegexOptions.IgnoreCase);
MatchCollection mactches = regx.Matches(a);
foreach (Match match in mactches)
{
string pattern = @"<(.|\n)*?>";
string r = Regex.Replace(match.Value, pattern, string.Empty);
textBox3.AppendText(r);
}
}
static string Fetch1(string pageURL)
{
HttpWebRequest WebReq = (HttpWebRequest)WebRequest.Create(pageURL);
WebReq.Method = "GET";
HttpWebResponse WebResp = (HttpWebResponse)WebReq.GetResponse();
Stream Answer = WebResp.GetResponseStream();
StreamReader _Answer = new StreamReader(Answer);
string myString = _Answer.ReadToEnd();
return myString;
}
void AfterFetch1(IAsyncResult result)
{
string a;
AsyncResult async = (AsyncResult)result;
UrlFetcher fetcher = (UrlFetcher)async.AsyncDelegate;
a = fetcher.EndInvoke(result).ToString();
Regex regx = new Regex(@"<td>([A-Za-z0-9\-]+)\.(com|net)</td>", RegexOptions.IgnoreCase);
MatchCollection mactches = regx.Matches(a);
foreach (Match match in mactches)
{
string pattern = @"<(.|\n)*?>";
string r = Regex.Replace(match.Value, pattern, string.Empty);
textBox3.AppendText(r);
}
}
}
}
如果有人会更正上述代码,我们非常感激。
由于
答案 0 :(得分:5)
我会说
(Begin/End)GetResponse
应该或多或少地工作