1

statusbar.cs

On load of StatusBar form,i am calling the backgroundWorker1.In backgroundWorker1.DoWork i am calling the Login(Username, Password); function which is also in the same statusbar.cs file.

private void StatusBar_Load(object sender, EventArgs e)
        {
            backgroundWorker1.RunWorkerCompleted += (o, args) =>
            {
                Close();
            };
            backgroundWorker1.DoWork +=
                (o, args) =>
                {
                    Login(Username, Password);

                };
            backgroundWorker1.RunWorkerAsync();
        }

Login(Username, Password)
{
  if(Authenticated)
  {   
     MessageBox.Show("Success");
     //do some process
  }
  else
  {
     MessageBox.Show("Failed...");
     return;
  }
}

My problem is progress bar is loading correctly.It is showing until i close the Messagebox.Once the OK button in messagebox is clicked the progress bar disappear.I need to hide the progress bar once the messagebox loads/shows.I tried putting backgroundWorker1.CancelAsync(); before the messagebox not worked for me.

I need to close the progress bar once the message box appear.Is it possible to terminate the backgroundworker1 forcibly.

user2681579
  • 1,413
  • 2
  • 23
  • 50
  • 1
    Post your actual code that compiles (that `Login` method is invalid). Also, where are you currently displaying / hiding the progress bar? – Grant Winney Sep 30 '14 at 15:36
  • 2
    The `CancelAsync` method just flags to the BackgroundWorker that the task needs to be cancelled. The actual work of cancelling must be done by your process inside the DoWork event. – Pradeep Kumar Sep 30 '14 at 15:38
  • 4
    Also, you should avoid any blocking methods like MessageBox etc. inside the DoWork. Instead `ReportProgress` and handle the `ProgressChanged` event. – Pradeep Kumar Sep 30 '14 at 15:39
  • 2
    You haven't shown us where you've used a progress bar? Also I don't see any reason to use `BackgroundWorker` for the posted code. Do you really make use of `BackgroundWorker` ? – Sriram Sakthivel Sep 30 '14 at 15:42
  • See this: http://stackoverflow.com/questions/800767/how-to-kill-background-worker-completely – Mehdi Khademloo Sep 30 '14 at 15:46

1 Answers1

0

The problem is that the CancelAsync method of the background worker, just set a variable inside the process that is working in another thread. Such process must check that variable and stop the action when it is set to false. This variable is in the DoWorkEventArgs and it is named Cancel.

If you can't control the flow of the action that you want to stop, then I recommend to use the classic Thread class. The Thread.Abort method raise a ThreadAbortException and force to the thread. to stop.

Raúl Otaño
  • 4,640
  • 3
  • 31
  • 65