Problem disabling Backgroundworker

Asked

Viewed 164 times

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 the backgroundWorker, but the method to 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;
}

Boot:

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

Deactivate button:

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

Event of the Do_work:

private void worker_DoWork(object sender, DoWorkEventArgs e)
{
     while(true)
     {
           ClienteBusiness.Inserir();
     }
}
  • He makes some mistake?

  • Do not give any error and even use Debug it goes through the worker.Cancelasync();

1 answer

3


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

Basically what the CancelAsync is to set the value of CancellationPending as true, then you should change your loop to check whether to cancel the operation.

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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.