【问题标题】:Background Worker is not stopping后台工作人员没有停止
【发布时间】:2012-10-20 19:16:50
【问题描述】:

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

这是我的工作方法...

【问题讨论】:

  • 您不需要 worker.CancelAsync() 和 if (worker.CancellationPending 部分,您可以不使用 BackgroundWorker。

标签: c# .net wpf multithreading backgroundworker


【解决方案1】:

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

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

编辑

从 DoWork 方法中设置 cancel 属性和 return -

if (worker.CancellationPending)
{
   e.Cancel = true;
   return;
}

【讨论】:

  • 好的,我试过这个。。同样的结果,它又回到了“尝试”的开头。无论如何,谢谢你的回答。。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-12-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多