Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Stopping background worker

My app uses background worker to go do some work inside a loop. I have it so that at each loop iteration, it checks if cancellation pending is true and if it is, breaks out the loop. All OK, my app stops processing once it is finished the current iteration of the loop. The problem is that I think the background worker is still running - if I click the button to start processing again, I get an error saying the background worker is busy.

I was going to dispose of the worker but then it is created when the form runs and so if I dispose of it, it is not there to start doing work again. What I really want to do is tell the background worker that it is complete, if I click a 'stop processing' button, so it is ready to start processing again when I click the start button!

I was going to try this:

private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e) 
{ 
    while (!backgroundWorker1.CancellationPending) 
    {
        // Start processing in a background thread so the GUI remains responsive,
        // pass in the name of the text file produced by 
        // PFDR FilenameLogic(txtLetterType.Text); 
    } 
}
like image 797
user1779064 Avatar asked Jun 16 '26 09:06

user1779064


2 Answers

When you create the worker, set worker.WorkerSupportsCancellation to true. Now inside the DoWork handler, you must periodically (most commonly, at the start of some loop, etc) check for worker.CancellationPending - if it is true, set e.Cancel = true; (so that you can distinguish completion from cancellation), clean-up, and exit (return;). Now your cancel button can invoke worker.CancelAsync(); and it will act appropriately.

like image 174
Marc Gravell Avatar answered Jun 19 '26 00:06

Marc Gravell


Same answer as Marc Gravell but you don't seem to follow.

Are you setting e.cancel = true?

        private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
        {
            BackgroundWorker worker = sender as BackgroundWorker;

            for (int i = 1; i <= 10; i++)
            {
                if (worker.CancellationPending == true)
                {
                    e.Cancel = true;
                    break;
                }
                else
                {
                    // Perform a time consuming operation and report progress.
                    System.Threading.Thread.Sleep(500);
                    worker.ReportProgress(i * 10);
                }
            }
        }
like image 24
paparazzo Avatar answered Jun 18 '26 23:06

paparazzo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!