继承问题

Dmi*_*iyd 1 c# inheritance winforms

我创建了一个类:

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;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

以下是我如何使用它:

  backgroundWorker1 = new AbortableBackgroundWorker();
//...
backgroundWorker1.RunWorkerAsync();

if (backgroundWorker1.IsBusy == true)
{
    backgroundWorker1.Abort();//This method is unavailable :(
    backgroundWorker1.Dispose();
}
Run Code Online (Sandbox Code Playgroud)

另一个小问题..这个代码会取消背景工作者吗?

Tho*_*que 6

这不是中止BackgroundWorker任务的正确方法...... 而是使用CancelAsync方法和CancellationPending属性.你应该几乎不会中止一个线程,至少在你可以干净地退出这个步骤时.