C#如何在没有cancelPending的情况下停止运行backgroundWorker

时间:2013-06-07 11:07:03

标签: c# backgroundworker cancellation

有没有办法在没有cancellationPending的情况下停止backgroundWorker线程? 我有这样的代码:

    DoWorkFunction
    {
    if(worker.cancellationPending == true) return; //this works great but

    VeryLongTimeComputingFunc();//this function take a lot of time and if it starts i can't stop it with cancellationPending
    ...Do something
    }

即使它启动了VeryLongTimeComputingFunc(),有没有办法阻止工作人员?

2 个答案:

答案 0 :(得分:0)

也许您可以在“VeryLongTimeComputingFunc”中触发“CancelWorker”事件,并在EventHandler中使用“worker.CancelAsync()”停止BackgroundWorker。

这应该有效:

  class BackgroundClass
    {
    public event EventHandler CancelWorker;

    BackgroundWorker worker = new BackgroundWorker();

    BackgroundClass()
    {
        CancelWorker += new EventHandler(BackgroundClass_CancelWorker);
    }

    void BackgroundClass_CancelWorker(object sender, EventArgs e)
    {
        worker.CancelAsync();
    }

    void RunBackgroundWorker()
    {   
        worker.DoWork += (sender, args) =>
        {
            VeryLongTimeComputingFunction();
        };
    }

    void VeryLongTimeComputingFunction()
    {
        if (CancelWorker != null)
        {
            CancelWorker(this, new EventArgs());
        }
    }
}

这将要求您可以在“VeryLongTimeComputingFunction()”

中更改某些内容

答案 1 :(得分:0)

假设您无法在VeryLongTimeComputingFunction内添加适当的取消支持,您最好的选择是保存对BGW主题的引用并在其上调用Abort。 请记住,这通常不建议,因为它可能涉及凌乱的清理。

为了安全起见,你应该抓住你长期职能中提出的任何ThreadAbortedException

private Thread bgThread;

void DoWorkFunction()
{
    bgThread = Thread.CurrentThread;
    try
    {
        VeryLongTimeComputingFunc();
    }
    catch (ThreadAbortedException e)
    {

        //do any necessary cleanup work.
        bgThread = null;
    }
}

void CancelBGW()
{
    if (bgThread != null)
    { 
        bgThread.Abort();
    }
}

根据CancelBGW的调用时间和方式,您可能还需要lock bgThread左右的作业。