在 form1 的顶部,我添加了:
System.Threading.ManualResetEvent _busy = new System.Threading.ManualResetEvent(true);
并且还在 form1 的顶部添加了两个标志:
bool pause;
bool resume;
这两个标志在构造函数中都设置为 false。
然后我有一个递归循环的函数:
private List<string> test(string url, int levels,DoWorkEventArgs eve)
{
if (pause == true)
{
_busy.Reset();
}
if (resume == true)
{
_busy.Set();
}
this.Invoke(new MethodInvoker(delegate { label3.Text = label3.Text = (Int32.Parse(label12.Text) + Int32.Parse(label10.Text)).ToString(); }));
HtmlWeb hw = new HtmlWeb();
List<string> webSites;
List<string> csFiles = new List<string>();
csFiles.Add("temp string to know that something is happening in level = " + levels.ToString());
csFiles.Add("current site name in this level is : " + url);
try
{
this.Invoke(new MethodInvoker(delegate { ColorText.Texts(richTextBox1, "Loading The Url: " , Color.Red); }));
this.Invoke(new MethodInvoker(delegate { ColorText.Texts(richTextBox1, url + "...",Color.Blue); }));
HtmlAgilityPack.HtmlDocument doc = TimeOut.getHtmlDocumentWebClient(url, false, "", 0, "", "");
this.Invoke(new MethodInvoker(delegate { ColorText.Texts(richTextBox1, " Done " + Environment.NewLine, Color.Red); }));
currentCrawlingSite.Add(url);
webSites = getLinks(doc);
removeDupes(webSites);
removeDuplicates(webSites, currentCrawlingSite);
removeDuplicates(webSites, sitesToCrawl);
if (removeExt == true)
{
for (int i = 0; i < webSites.Count; i++)
{
webSites.Remove(removeExternals(webSites));
}
}
if (downLoadImages == true)
{
webContent.retrieveImages(url); }
if (levels > 0)
sitesToCrawl.AddRange(webSites
this.Invoke(new MethodInvoker(delegate { label7.Text = sitesToCrawl.Count.ToString(); }));
this.Invoke(new MethodInvoker(delegate { label12.Text = currentCrawlingSite.Count.ToString(); }));
if (levels == 0)
{
return csFiles;
}
else
{
for (int i = 0; i < webSites.Count(); i++)//&& i < 20; i++) {
string t = webSites[i];
if ((t.StartsWith("http://") == true) || (t.StartsWith("https://") == true)) // replace this with future FilterJunkLinks function
{
csFiles.AddRange(test(t, levels - 1, eve));
}
}
return csFiles;
}
}
catch
{
failedUrls++;
this.Invoke(new MethodInvoker(delegate { label10.Text = failedUrls.ToString(); }));
this.Invoke(new MethodInvoker(delegate { ColorText.Texts(richTextBox1, " Failed " + Environment.NewLine, Color.Green); }));
return csFiles;
}
}
在后台工作人员 DoWork 事件中,我添加了以下内容:
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
_busy.WaitOne();
this.Invoke(new MethodInvoker(delegate { label2.Text = "Website To Crawl: "; }));
this.Invoke(new MethodInvoker(delegate { label4.Text = mainUrl; }));
test(mainUrl, levelsToCrawl, e);
}
然后我有两个按钮单击事件,一个用于暂停,一个用于恢复:
private void button4_Click(object sender, EventArgs e)
{
pause = true;
}
private void button5_Click(object sender, EventArgs e)
{
resume = true;
}
但是当我点击按钮暂停时,恢复按钮上也没有任何反应。这个过程还在继续。我也尝试在每个按钮中不使用标志来制作 _busy.Reset(); 和 _busy.Set(); 但什么都没有。
我想要的是以某种方式暂停递归循环并恢复它。我不确定它是否连接到后台工作人员,但想法是暂停并恢复该过程。
我该怎么办 ?
谢谢。