Search code examples
c#backgroundworker

Request using BackgroundWorker never seems to complete


I created a Loading Window for my Login form, and I use BackgroundWorker to make a smooth Loading animation, but if I use ShowDialog() insted of Show(), the Loading Window stays on screen, and the program does nothing. What's causing this?

Here I invoke the BackgroundWorker and I show the Loading page:

private void loginButton_Click(object sender, EventArgs e) {
    loadscr.Show();
    LoginBV.RunWorkerAsync();
}

and here I close the Loading Window:

private void LoginBV_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e) {
    loadscr.Close();
    //and show the MainWindow, etc.
}

The DoWork(BackgroundWorker) code:

    private void LoginBV_DoWork(object sender, DoWorkEventArgs e) {
        NameValueCollection POST = new NameValueCollection();
        POST["username"] = ipbUN.Text;
        POST["password"] = ipbPASS.Text;
        POST["pin"] = ipbPIN.Text;
        POST["csoport"] = "user";

        var action = Program.startPOST<DataObj>("http://localhost/system/winapi.php?do=userlogin", POST);

        finish["sessionkey"] = action.sessionkey;
        finish["status"] = Convert.ToString(action.status);
    }

Solution

  • See MSDN article on ShowDialog.

    "You can use this method to display a modal dialog box in your application. When this method is called, the code following it is not executed until after the dialog box is closed."

    Using modal dialogs (ShowDialog) stops the execution of the code following it until something/someone dismisses the dialog. It "pauses" your program. The background worker is never run because you start it after calling ShowDialog.