1

我有一个后台工作人员的应用程序。在 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) { }

这是我的工作方法...

4

1 回答 1

6

您需要设置worker.WorkerSupportsCancellationtrue. 默认值为false。在运行之前将属性设置为 true -

BackgroundWorker worker = new BackgroundWorker();
worker.WorkerSupportsCancellation = true;
worker.RunWorkerAsync();

编辑

设置cancel属性并return从 DoWork 方法 -

if (worker.CancellationPending)
{
   e.Cancel = true;
   return;
}
于 2012-10-20T19:23:34.770 回答