C# 使用backgroundworker问题需要帮助来解决此问题
当我按下btn_Connect时,backgroundworker将启动,但当它到达时,在我单击messagebox上的ok后提示messagebox,它将再次运行并显示messagebox,当我再次单击btn_Connect时,它将执行相同的操作,并且它将递增,因此第一次单击是第二次单击btn_Connect时显示messagebox的两倍三次。如何解决这个问题, 这是我的密码:C# 使用backgroundworker问题需要帮助来解决此问题,c#,backgroundworker,C#,Backgroundworker,当我按下btn_Connect时,backgroundworker将启动,但当它到达时,在我单击messagebox上的ok后提示messagebox,它将再次运行并显示messagebox,当我再次单击btn_Connect时,它将执行相同的操作,并且它将递增,因此第一次单击是第二次单击btn_Connect时显示messagebox的两倍三次。如何解决这个问题, 这是我的密码: private void testConnection() { backgroundWor
private void testConnection()
{
backgroundWorker.ReportProgress(15);
txt.createConnectionFile(txtServerName.Text, txtDatabase.Text, txtUserName.Text, txtPassword.Text);
backgroundWorker.ReportProgress(30);
cn.createConnection();
backgroundWorker.ReportProgress(60);
try
{
backgroundWorker.ReportProgress(80);
cn.openConnection();
MessageBox.Show("Connected!", "Connection Success", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Connection Error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
}
backgroundWorker.ReportProgress(100);
}
private void backgroundWorker_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
progressBar.Value = e.ProgressPercentage;
}
private void backgroundWorker_DoWork(object sender, DoWorkEventArgs e)
{
testConnection();
}
private void btnConnect_Click(object sender, EventArgs e)
{
progressBar.Visible = true;
backgroundWorker.WorkerReportsProgress = true;
backgroundWorker.WorkerSupportsCancellation = true;
backgroundWorker.ProgressChanged += backgroundWorker_ProgressChanged;
backgroundWorker.DoWork += backgroundWorker_DoWork;
backgroundWorker.RunWorkerAsync();
}
我注意到的一点是,每次单击按钮时,您都会连接DoWork和RunWorkerCompleted事件 根据上面的代码,我怀疑第一次单击按钮时它会运行一次,然后按钮会再次启用。下次单击按钮时,它将运行两次,下次运行三次,以此类推 您需要在单击按钮之外连接事件。例如,在OnLoad中 如果无法执行此操作,请将单击代码替换为
private void btnConnect_Click(object sender, EventArgs e)
{
progressBar.Visible = true;
backgroundWorker.WorkerReportsProgress = true;
backgroundWorker.WorkerSupportsCancellation = true;
backgroundWorker.ProgressChanged -= backgroundWorker_ProgressChanged;
backgroundWorker.ProgressChanged += backgroundWorker_ProgressChanged;
backgroundWorker.DoWork -= backgroundWorker_DoWork;
backgroundWorker.DoWork += backgroundWorker_DoWork;
backgroundWorker.RunWorkerAsync();
}