当我按下btn_Connect时,后台工作人员会在它到达它时提示消息框,然后我在消息框上单击确定它将再次运行并再次显示消息框,当我再次单击btn_Connect时它会执行相同的操作并且会增加第一个点击是两次,第二次点击btn_Connect将显示消息框三次。如何解决这个问题,
这是我的代码:
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();
}
答案 0 :(得分:1)
我注意到的一件事是,每次单击按钮时,您都会连接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();
}