我有一个后台工作者的应用程序。在doWork方法中,我执行html Web请求。如果该请求失败(例如错误404),我想在完成之前退出该线程。所以在我的捕获中我添加了这段代码
worker.CancelAsync();
if (worker.CancellationPending)
{
e.Cancel = true;
}
问题是线程没有停止,但它会创建一个新的html Web请求。
一些代码:
try
{
var request = (HttpWebRequest)WebRequest.Create(url1);
request.Timeout = 5000;
request.UserAgent = @"Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US; rv:1.9.1.5) Gecko/20091102 Firefox/3.5.5";
var document = new HtmlAgilityPack.HtmlDocument();
try
{
using (var responseStream = request.GetResponse().GetResponseStream())
{
document.Load(responseStream, Encoding.UTF8);
//some lines of code to parse html
}
catch (WebException we){
worker.CancelAsync();
if (worker.CancellationPending)
{
e.Cancel = true;
return;
}
}
catch (Exception) { }
这是我的工作方法......
答案 0 :(得分:6)
您需要将worker.WorkerSupportsCancellation
设置为true
。 Defualt值为false
。
在运行之前将属性设置为true -
BackgroundWorker worker = new BackgroundWorker();
worker.WorkerSupportsCancellation = true;
worker.RunWorkerAsync();
修改强>
从DoWork方法设置cancel
属性和return
-
if (worker.CancellationPending)
{
e.Cancel = true;
return;
}