I have an application with a background worker. In the doWork method i do a html web request. If this request failed (eg error 404), i want to exit from the thread before it finishes. So in my catch i added this code
worker.CancelAsync();
if (worker.CancellationPending)
{
e.Cancel = true;
}
The problem is that the thread does not stop, but it creates a new html web request.
Some code:
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) { }
This is my do work method...
You need to set worker.WorkerSupportsCancellation
to true
. Defualt value is false
. Set the property to true before running it -
BackgroundWorker worker = new BackgroundWorker();
worker.WorkerSupportsCancellation = true;
worker.RunWorkerAsync();
Edit
Set the cancel
property and return
from the DoWork method -
if (worker.CancellationPending)
{
e.Cancel = true;
return;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.