感谢大家,我设法使用 Dictionary 而不是 Hashset 解决了这个问题,并使用 Key 来保存 URL ,并使用保存 int 的值,如果 url 被扫描,则为 1 ,如果 url 仍未处理,则为 0 ,下面是我的代码。
我使用另一个字典“URL_CANtoSave”来保存以 jpg“my target”结尾的 url...并且这个 While 循环..可以循环,直到根据您在过滤器字符串变量中指定的值耗尽网站的所有 url您相应地解析网址。
因此,要打破循环,您可以指定要在 URL_CantoSave 中获取的图像 url 数量。
return Task.Factory.StartNew(() =>
{
try
{
string tempURL;
int i = 0;
// 我以前设置Dictionary Key的值,1或0(1表示扫描,
0 表示尚未,并进行迭代,直到扫描完所有词典键,或者根据您在其他词典中收集的图像 url 数量在中间中断
while (URL_Can.Values.Where(value => value.Equals(0)).Any())
{
// 获取 1 个密钥并将其放入临时变量中
tempURL = URL_Can.ElementAt(i).Key;
// 检查它是否以您的目标文件扩展名结尾。在本例中为图像文件
if (tempURL.EndsWith("jpg"))
{
URL_CanToSave.Add(tempURL,0);
URL_Can.Remove(tempURL);
}
// 如果不是图片则根据url下载页面并继续分析
else
{
// 如果之前没有扫描过url
if (URL_Can[tempURL] != 1)
{
// 这里看起来有点复杂,其中 Add2Dic 是添加到字典的过程,而无需再次添加密钥(解决主要问题!!)
“ExtractURLfromLink”是另一个过程,它返回字典,其中包含通过下载 url 的文档字符串并分析它来分析的所有链接,
您可以根据您的分析添加删除过滤字符串
Add2Dic(ExtractUrlsfromLink(client, tempURL, filterlink1), URL_Can, false);
Add2Dic(ExtractUrlsfromLink(client, tempURL, filterlink2), URL_Can, false);
URL_Can[tempURL] = 1; // to set it as scanned link
richTextBox2.PerformSafely(() => richTextBox2.AppendText(tempURL + "\n"));
}
}
statusStrip1.PerformSafely(() => toolStripProgressBar1.PerformStep());
// 这里还有另一个技巧,可以让迭代继续进行,直到扫描完所有收集到的链接
i++; if (i >= URL_Can.Count) { i = 0; }
if (URL_CanToSave.Count >= 150) { break; }
}
richTextBox2.PerformSafely(() => richTextBox2.Clear());
textBox1.PerformSafely(() => textBox1.Text = URL_Can.Count.ToString());
return ProcessCompleted = true;
}
catch (Exception aih)
{
MessageBox.Show(aih.Message);
return ProcessCompleted = false;
throw;
}
{
richTextBox2.PerformSafely(()=>richTextBox2.AppendText(url+"\n"));
}
})