0

is there any way to stop backgroundWorker thread without cancellationPending? I have code like this:

    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
    }

Is there any way to stop worker even if it started VeryLongTimeComputingFunc()?

2 Answers2

0

Maybe you could fire an "CancelWorker" event in your "VeryLongTimeComputingFunc" and in the EventHandler you stop the BackgroundWorker with "worker.CancelAsync()".

This should work:

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

This would require that you can change something in the "VeryLongTimeComputingFunction()"

Philipp Eger
  • 2,235
  • 4
  • 23
  • 34
0

Assuming you can not add proper cancellation support inside VeryLongTimeComputingFunction, your best option is to save a reference to the BGW's thread and call Abort on it. Keep in mind this is not generally recommended as it may involve a messy cleanup.

To be safe, you should catch any ThreadAbortedException raised in your long function.

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

Depending on when and how CancelBGW is called, you may also need a lock around assignments of bgThread.

Rotem
  • 21,452
  • 6
  • 62
  • 109