在这种情况下,progressBar 的移动速度比真正的 Dowork 进度更快,然后在 progressChanged 事件中抛出异常,即 progressBar 值超过 100%,那么这里有什么问题我如何以正确的方式计算和报告它?
private List<string> webCrawler(string url, int levels , DoWorkEventArgs eve)
{
bool already = false;
HtmlAgilityPack.HtmlDocument doc;
HtmlWeb hw = new HtmlWeb();
List<string> webSites;// = new List<string>();
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
{
doc = hw.Load(url);
webSites = getLinks(doc);
if (levels == 0)
{
return csFiles;
}
else
{
int actual_sites = 0;
for (int i = 0; i < webSites.Count() && i < 20; i++) {
if ((worker.CancellationPending == true))
{
eve.Cancel = true;
break;
}
else
{
string t = webSites[i];
if ((t.StartsWith("http://") == true) || (t.StartsWith("https://") == true)) // replace this with future FilterJunkLinks function
{
for (int e = 0; e < csFiles.Count; e++)
{
if (csFiles[e].Contains(t))
{
already = true;
}
}
if (!already)
{
actual_sites++;
csFiles.AddRange(webCrawler(t, levels - 1,eve));
this.Invoke(new MethodInvoker(delegate { Texts(richTextBox1, "Level Number " + levels + " " + t + Environment.NewLine, Color.Red); }));
worker.ReportProgress(i * 10);
}
}
}
}
return csFiles;
}
}
catch
{
return csFiles;
}
}
public void Texts(RichTextBox box, string text, Color color)
{
box.SelectionStart = box.TextLength;
box.SelectionLength = 0;
box.SelectionColor = color;
box.AppendText(text);
box.SelectionColor = box.ForeColor;
}
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
worker = sender as BackgroundWorker;
webCrawler(guys, 2,e);
}
private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
this.progressBar1.Value = e.ProgressPercentage;
}
private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
}
private void button1_Click(object sender, EventArgs e)
{
backgroundWorker1.RunWorkerAsync();
}
我在 DoWork 事件中传递了 DoWorkEventsArgs 的变量 e,因此如果我需要取消操作,我可以在 webCrawler 函数中使用工作变量。在 webCrawler 中,我称它为 DoWorkEventArgs 前夕。
问题是向progressBar 的报告不是正确的方法。
尝试报告进度为:
for (int i = 0; i < webSites.Count() && i < 20; i++) {
double incPercent = (1 / webSites.Count());
if ((worker.CancellationPending == true))
{
eve.Cancel = true;
break;
}
else
{
string t = webSites[i];
if ((t.StartsWith("http://") == true) || (t.StartsWith("https://") == true)) // replace this with future FilterJunkLinks function
{
for (int e = 0; e < csFiles.Count; e++)
{
if (csFiles[e].Contains(t))
{
already = true;
}
}
if (!already)
{
actual_sites++;
csFiles.AddRange(webCrawler(t, levels - 1,eve));
this.Invoke(new MethodInvoker(delegate { Texts(richTextBox1, "Level Number " + levels + " " + t + Environment.NewLine, Color.Red); }));
worker.ReportProgress(i * (int)incPercent);