继承问题

时间:2011-07-21 14:51:28

标签: c# winforms inheritance

我创建了一个类:

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;
        }
    }
}

以下是我如何使用它:

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

if (backgroundWorker1.IsBusy == true)
{
    backgroundWorker1.Abort();//This method is unavailable :(
    backgroundWorker1.Dispose();
}

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

2 个答案:

答案 0 :(得分:6)

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

答案 1 :(得分:1)

该方法不可用,因为backgroundWorker1的静态类型为BackgroundWorker。你需要

AbortableBackgroundWorker backgroundWorker1 = new AbortableBackgroundWorker();

否则,您必须将其转发((cast)as)至AbortableBackgroundWorker