Problem when you disable Backgroundworker

0

I am creating in my main form a BackgroundWorker object and I have two click events, one to activate and the other to disable backgroundWorker, but the method of disable is not working.

BackgroundWorker worker;
public FrmPrincipal()
{
   InitializeComponent();
   worker = new BackgroundWorker();
   worker.DoWork += worker_DoWork;
   worker.WorkerReportsProgress = true;
   worker.WorkerSupportsCancellation = true;
   worker.ProgressChanged += worker_ProgressChanged;
   worker.RunWorkerCompleted += worker_RunWorkerCompleted;
}

Activate button:

private Ativar_Click()
{
   worker.RunWorkerAsync();
}

Deactivate button:

private Desativar_Click()
{
   worker.CancelAsync();
}

Do_Work Event:

private void worker_DoWork(object sender, DoWorkEventArgs e)
{
     while(true)
     {
           ClienteBusiness.Inserir();
     }
}
    
asked by anonymous 06.03.2017 / 22:29

1 answer

3

This happens because CancelAsync only signals the cancellation, it is still your obligation to stop what is being executed.

Basically what CancelAsync does is set the value of CancellationPending to true , so you should change your loop to see if you should cancel the operation.

private void worker_DoWork(object sender, DoWorkEventArgs e)
{
    while(!worker.CancellationPending)
    {
        ClienteBusiness.Inserir();
    }
}
    
07.03.2017 / 14:48