我正在尝试制作一个多线程网络刮板。为此,我正在使用 Parallel.For。这是我的代码:
string source = "http://www.lolsummoners.com/ladders/eune/";
string regex_Search = "leagues/.*>(.*)</a></td>";
List<string> user_List = new List<string>();
int page_Begin = 1;
int page_End = 10;
ParallelOptions p_Option = new ParallelOptions();
p_Option.MaxDegreeOfParallelism = 3;
Parallel.For(page_Begin, page_End, p_Option, index =>
{
try
{
WebClient web = new WebClient();
web.Encoding = Encoding.UTF8;
String html = web.DownloadString(source + page_Begin);
MatchCollection matches = Regex.Matches(html, @regex_Search);
foreach(Match match_Find in matches)
{
string user = match_Find.Groups[1].Value.Replace(" ", string.Empty);
user_List.Add(user);
Console.WriteLine(user);
}
}
catch(Exception e)
{
Console.WriteLine(e.Message);
}
page_Begin++;
});
Console.ReadKey();
我的问题是,如果我使用多个线程,我会得到重复。有没有办法解决这个问题?我不需要循环从同一个网页获取相同的名称,这就是为什么我增加 page_Begin 变量结束。这就是我要说的: