Below is my coding:
Form2 msgForm;
private void button3_Click_1(object sender, EventArgs e)
{
bw.WorkerReportsProgress = true;
bw.WorkerSupportsCancellation = true;
bw.DoWork += new DoWorkEventHandler(bw_DoWork);
bw.RunWorkerCompleted += new RunWorkerCompletedEventHandler(bw_RunWorkerCompleted);
msgForm = new Form2();
try
{
bw.RunWorkerAsync();
msgForm.ShowDialog();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
void bw_DoWork(object sender, DoWorkEventArgs e)
{
// Coding that transmit protocol and will last around 2 minutes.
}
void bw_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
msgForm.Close();
}
I use the background worker method everytime I click a button to transmit protocols that last around 2 minutes. During transmission, the From2 will show ‘Please wait’.
But I have some problem using this coding. The problem is like, when I click the button the first time, it will transmit the protocol once. After that I click again which is the second time, it transmit the protocol twice. After that I click again which is the third time, it transmit the protocol 3 times…. And so on. The times of protocol of transmit increase each time I click the button.
Aren’t that it will only run once the coding in void bw_DoWork everytime I click the button?
Is there something wrong with my coding?
You’re appending an additional handler every time you click, and then it’s run along with everything you added before, which stays where it is (because the object is still there, you’re re-using it).
To solve this, you need to either:
DoWorkhandlerLike this:
.DoWork += ...which appends the handler in the constructor of the classIt mostly depends on if you use that worker somewhere else.