0

I have a backgroundworker. When it start it call a method to send record from a database to another webservice.

Problem is I made a stop button to stop the job sending but it didn't work.

I try to dispose backgroundworker or CancelAsync but that method still running (My app is a windows form app so I know that method is still running). Anyone can give me a solution for this ? Tks so much!

My code :

 private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
        {
            Send();
        }

Stop button

private void btnStop_Click(object sender, EventArgs e)
        {            
            try
            {
               backgroundWorker1.CancelAsync();   
               backgroundWorker1.Dispose();                                
            }
            catch (Exception ex)
            {
                Global._logger.Info(ex.Message + ex.Source);
                ShowError(ex.Message);
            }

        }

Note : The method Send() will call another method to send record after checking DB.

Đức Bùi
  • 517
  • 1
  • 6
  • 22
  • 2
    I ran into the same issue with running an infinite loop. What I ended up doing was creating a volatile flag and just changing its values when I wanted all threads to stop. This caused the loop to exit and the threads to exit on their own. – Steve's a D Dec 12 '12 at 03:57
  • @Steve: Yeah, tks I'm just thought of that :) and I answered my own question :) – Đức Bùi Dec 12 '12 at 04:00
  • this is a very duplicated question. One such [Cancel backgroundworker](http://stackoverflow.com/questions/3255459/cancel-backgroundworker). Always do a basic SO search before posting – nawfal Dec 12 '12 at 04:06

3 Answers3

1

This all depends on what Send is doing. You need to pass the BackgroundWorker instance into this method and check the CancellationPending property (which is set after calling CancelAync). If Send is using some sort of async post or even a bulk one you won't be able to cancel it. You have to be able to inspect this property at some point to stop whatever it is that you're doing.

Simon Whitehead
  • 63,300
  • 9
  • 114
  • 138
0

Ok, i found it :) I dont need to do anything with backgroundworker just dispose it and create a global variable as a flag to terminal the loop in method that method Send() call

Đức Bùi
  • 517
  • 1
  • 6
  • 22
0
if(worker.IsBusy)
{
    worker.CancelAsync();
}
else
{
    worker.RunWorkerAsync();
}   
James Shaw
  • 839
  • 1
  • 6
  • 16