Gui O
Gui O

Reputation: 383

C# Backgroundworker closing form

I am having an issue with a background worker. When i'm cancelling the backgroundworker, it closes the form too, i don't want it. I just want to stop the backgroundworker, and keep the form on the screen, and saying a message to the user like "Program stopped by user"

public BackgroundWorker bw = new BackgroundWorker() { WorkerSupportsCancellation = true };
public Form1()
        {
            bw.WorkerSupportsCancellation = true;
            InitializeComponent();
        }

private void stopChild_Click(object sender, EventArgs e)
        {
            if (bw.IsBusy)
            {
                bw.CancelAsync();
                this.Dispose();
            }
        }

public void startParListe()
        {
            bw.DoWork += new DoWorkEventHandler(bw_DoWork);
            if (bw.IsBusy != true)
                bw.RunWorkerAsync();
        }

public void bw_DoWork(object sender, DoWorkEventArgs e)
{
    BackgroundWorker worker = sender as BackgroundWorker ;
    for (int i = 0; i < countPlages; i++)
    {
         if ((worker.CancellationPending == true)) 
         {
             e.Cancel = true;
         }
         #do something else
    }
}

So, when the user click on the "stopChild" button, it is supposed to send a CancelSignal to my BWorker. Everytime my BWorker is working, i'm checking for this CancellationPending Signal before doing anything.

With this code, the form closes when clicking on the "stopChild" And when i remove the "this.Dispose()", the BWorker doesn't stop. Why ?

Upvotes: 0

Views: 1912

Answers (2)

chiccodoro
chiccodoro

Reputation: 14716

You don't properly process the CancellationPending:

     if ((worker.CancellationPending == true)) 
     {
         e.Cancel = true;
     }

I am not sure what e.Cancel is supposed to do, but you still continue to do work in your for loop since you don't leave the loop. Change it to:

     if (worker.CancellationPending) // btw - avoid unnecessarily verbous code
     {
         break;
     }

The backgroundworker does not close your form, this.Dispose does. You need to omit it. The reason why this.Dispose helped stop the background worker is because it is owned by the form, so closing the form also closees the worker. But once you fix the cancellation as described above, you should not need Dispose any longer

Upvotes: 2

Michael B
Michael B

Reputation: 581

You should break out of the loop when you set e.Cancel to true (also, this.Dispose() is closing your form:

public void bw_DoWork(object sender, DoWorkEventArgs e)
{
    BackgroundWorker worker = sender as BackgroundWorker ;
    for (int i = 0; i < countPlages; i++)
    {
         if ((worker.CancellationPending == true)) 
         {
             e.Cancel = true;
             break;
         }
         #do something else
    }

}

Upvotes: 0

Related Questions