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