【发布时间】:2015-08-25 10:18:53
【问题描述】:
我在实现从 stackowerflow 获得的关于杀死后台工作进程的代码时遇到问题。
我的代码如下:
using System;
using System.Collections.Generic;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
using System.Threading;
using System.Text.RegularExpressions;
using System.Runtime.InteropServices;
using GluthGUI.Classes.XMLprofile;
using System.Xml.Linq;
using System.ComponentModel;
namespace Solution
{
partial class SolGUI : Form
{
private void startButton_Click(object sender, EventArgs e)
{
backgroundWorker1 = new AbortableBackgroundWorker();
if (startButton.Text == "Start")
{
XMLParsing();
DisableTextFields();
backgroundWorker1.RunWorkerAsync();
startButton.Text = "Stop";
}
else if (startButton.Text == "Stop")
{
if (backgroundWorker1.IsBusy == true)
{
backgroundWorker1.Abort(); //error Abort() is not declared?!?!
backgroundWorker1.Dispose();
}
startButton.Text = "Start";
DisableTextFields();
}
}
}
这是一个将终止 backgroundworker 的部分类:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.ComponentModel;
using System.Threading;
namespace Solution
{
public class AbortableBackgroundWorker : BackgroundWorker
{
private Thread workerThread;
protected override void OnDoWork(DoWorkEventArgs e)
{
workerThread = Thread.CurrentThread;
try
{
base.OnDoWork(e);
}
catch (ThreadAbortException)
{
e.Cancel = true; //We must set Cancel property to true!
Thread.ResetAbort(); //Prevents ThreadAbortException propagation
}
}
public void Abort()
{
if (workerThread != null)
{
workerThread.Abort();
workerThread = null;
}
}
}
}
我的问题是部分类的 Abort() 方法在具有相同命名空间的其他类中不可见。
【问题讨论】:
-
你真的需要使用 Abort 吗?在大多数情况下不建议这样做。而是使用变量或 CancellationToken。
-
在非部分类中使用 AbortableBackgroundWorker 是否有效?
-
backgroundWorker1在哪里(以及如何)定义?类型是AbortableBackgroundWorker?而且它永远不会很忙,因为你每次都在创建一个新实例,所以你永远不会有任何事情要中止 -
As Eric Lippert says: Thread.Abort 充其量是糟糕设计的表现,可能不可靠且极其危险。应该不惜一切代价避免它
-
'System.ComponentModel.BackgroundWorker' 不包含'Abort' 的定义,并且找不到接受'System.ComponentModel.BackgroundWorker' 类型的第一个参数的扩展方法'Abort'(你是缺少 using 指令或程序集引用?)
标签: c# class methods backgroundworker