带有进度条的BackroundWorker不会触发RunWorkerCompleted

时间:2015-05-26 14:00:11

标签: c# asynchronous sqlconnection

我知道之前已经问过这个问题,但我找不到答案。我有一个backroundworker加载进度条并执行一个检查sql连接的方法。

private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
          {
              BackgroundWorker worker = sender as BackgroundWorker;

          for (int i = 1; (i <= 100); i++)
          {
                  // Perform a time consuming operation and report progress.
                  System.Threading.Thread.Sleep(25);
                  worker.ReportProgress((i));

                  if ( i == 75) 
                  CheckConnection();
          }


      }

      private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
      {

          this.progressBar1.Value = e.ProgressPercentage;
      }

      private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
      {
          MessageBox.Show("Checked");
      }

CheckConnection方法

 private void CheckConnection()
    {
        string response = "";
        //Check if Windows authentification or SQL Autentificaion and create the connection string
        if (AuthMode == 1)
        {
            ConnectionString = "Data Source=" + Server + ";Initial Catalog=master;Integrated Security=SSPI;";
        }
        else
        {
            ConnectionString = "Data Source=" + Server + ";Initial Catalog=master;User ID=" + Username + ";Password=" + Password+ "";
        }

        SqlConnection connection = new SqlConnection(ConnectionString);

        try
        {
            connection.Open();
            response = "Connection successfull for: " + ConnectionString;
        }
        catch (InvalidOperationException e)
        {
            response = "Connection failed for: " + ConnectionString + e.Message;
            MessageBox.Show(response);

        }
        catch (SqlException e)
        {
            response = "Connection failed for: " + ConnectionString + e.Message;
            MessageBox.Show(response);

        }
        catch (Exception e)
        {
            response = "Connection failed for: " + ConnectionString + e.Message;
            MessageBox.Show(response);

        }

    }

进度条加载很好,但RunWorkerCompleted不会触发。知道为什么吗?感谢

编辑: 我在点击按钮时调用backroundWorker1.RunWorkerAsync()。

 private void btnChkCon_Click(object sender, EventArgs e)
        {
          backgroundWorker1.RunWorkerAsync(); 
        }

修改

发现问题,backgroundWorker1_RunWorkerCompleted没有绑定到BackroundworkerCompleted事件,现在可以正常工作。

0 个答案:

没有答案