0

当我按下 btn_Connect 时,backgroundworker 会,但是当它到达它时,在我单击消息框上的确定后提示消息框,它将再次运行并再次显示消息框,当我再次单击 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();
    }
4

1 回答 1

1

我注意到的一件事是,每次单击按钮时,您都会继续连接 DoWork 和 RunWorkerCompleted 事件。

根据上面的代码,我怀疑第一次单击按钮时它会运行一次,然后该按钮会再次启用。下次单击按钮时,它将运行两次,下一次运行 3 次,以此类推。

您需要连接按钮单击之外的事件。例如在 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();
    }
于 2012-11-22T05:45:42.723 回答