ObjectDisposedException 被捕获。
无法访问已处置的对象。对象名称:'Form1'。
那是当后台工作人员正在工作时,我单击右上角的 X 红色 X 以关闭应用程序,当它处于工作中间时,有时它会抛出此异常。
System.ObjectDisposedException was caught
Message=Cannot access a disposed object.
Object name: 'Form1'.
Source=System.Windows.Forms
ObjectName=Form1
StackTrace:
at System.Windows.Forms.Control.MarshaledInvoke(Control caller, Delegate method, Object[] args, Boolean synchronous)
at System.Windows.Forms.Control.Invoke(Delegate method, Object[] args)
at System.Windows.Forms.Control.Invoke(Delegate method)
at GatherLinks.Form1.test(String url, Int32 levels, DoWorkEventArgs eve) in D:\C-Sharp\GatherLinks\GatherLinks\GatherLinks\Form1.cs:line 126
InnerException:
在这种情况下,第 126 行是:
this.Invoke(new MethodInvoker(delegate { Texts(richTextBox1, " Done " + Environment.NewLine, Color.Red); }));
我应该如何修复/修复此异常以及退出应用程序时应该释放/关闭哪些对象或变量?
测试功能:
private List<string> test(string url, int levels,DoWorkEventArgs eve)
{
levels = levelsToCrawl;
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 { Texts(richTextBox1, "Loading The Url: " + url + "..." , Color.Red); }));
HtmlAgilityPack.HtmlDocument doc = GetHtmlDoc(url, reqOptions, null);
if (timeOut == true)
{
this.Invoke(new MethodInvoker(delegate { Texts(richTextBox1, " There Was A TimeOut" + Environment.NewLine , Color.Red); }));
timeOut = false;
return csFiles;
}
else
{
this.Invoke(new MethodInvoker(delegate { Texts(richTextBox1, " Done " + Environment.NewLine, Color.Red); }));
}
currentCrawlingSite.Add(url);
webSites = getLinks(doc);
removeDupes(webSites);
removeDuplicates(webSites, currentCrawlingSite);
removeDuplicates(webSites, sitesToCrawl);
if (removeExt == true)
{
removeExternals(webSites);
}
if (downLoadImages == true)
{
retrieveImages(url); }
if (levels > 0)
sitesToCrawl.AddRange(webSites
this.Invoke(new MethodInvoker(delegate { label7.Text = sitesToCrawl.Count.ToString(); }));
this.Invoke(new MethodInvoker(delegate { label3.Text = currentCrawlingSite.Count().ToString(); }));
if (levels == 0)
{
return csFiles;
}
else
{
for (int i = 0; i < webSites.Count(); i++)//&& i < 20; i++) {
int mx = Math.Min(webSites.Count(), 20);
string t = webSites[i];
if ((t.StartsWith("http://") == true) || (t.StartsWith("https://") == true))
{
csFiles.AddRange(test(t, levels - 1, eve));
}
}
return csFiles;
}
}
catch
{
return csFiles;
}
}
以及后台工作者 DoWork 和 ProgressReport 事件:
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
this.Invoke(new MethodInvoker(delegate { label2.Text = "Website To Crawl: "; }));
this.Invoke(new MethodInvoker(delegate { label4.Text = mainUrl; }));
test(mainUrl, levelsToCrawl, e);
}
private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
}