c#如何停止运行backgroundWorker而不使用cancellationPending

本文关键字:cancellationPending backgroundWorker 何停止 运行 | 更新日期: 2023-09-27 18:17:33

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

    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()?

c#如何停止运行backgroundWorker而不使用cancellationPending

也许你可以在你的"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() "中改变一些东西"

假设你不能在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,您可能还需要在bgThread的赋值周围使用lock

相关文章:
  • 没有找到相关文章