Hi,
I have a special problem that I wonder how it could be possible to solve.
I have 2 backgroundworkers that I know are, asynchronous events. I start the 2 backgroundworkers with the startButton. The workers have a loop with Thread.Sleep(1).
With the setFlagButton, I set the variable like this: block = "notbusy";
In this moment, I want only one of the backgroundworkers to report progress and show the messageBox. Either MessageBox.Show("From a1") or MessageBox.Show("From a2").
Sometimes only one of the messageboxes are shown but sometimes both are shown. How can this be solved so only one messagebox will be shown each time?
private void setFlagButton_Click(object sender, EventArgs e)
{
block = "notbusy";
}
BackgroundWorker a1 = new BackgroundWorker();
BackgroundWorker a2 = new BackgroundWorker();
String block = "";
private void startButton_Click(object sender, EventArgs e)
{
block = "busy";
//Activate Workers
if (a1.IsBusy == false)
{
a1 = new BackgroundWorker();
a1.WorkerReportsProgress = true;
a1.DoWork += new DoWorkEventHandler(a1_DoWork);
a1.ProgressChanged += new ProgressChangedEventHandler(a1_ProgressChanged);
a1.RunWorkerAsync();
}
if (a2.IsBusy == false)
{
a2 = new BackgroundWorker();
a2.WorkerReportsProgress = true;
a2.DoWork += new DoWorkEventHandler(a2_DoWork);
a2.ProgressChanged += new ProgressChangedEventHandler(a2_ProgressChanged);
a2.RunWorkerAsync();
}
}
private void a1_DoWork(object sender, DoWorkEventArgs e)
{
while (true)
{
while (block == "busy")
{
Thread.Sleep(1);
}
block = "busy";
a1.ReportProgress(1);
}
}
private void a2_DoWork(object sender, DoWorkEventArgs e)
{
while (true)
{
while (block == "busy")
{
Thread.Sleep(1);
}
block = "busy";
a2.ReportProgress(1);
}
}
private void a1_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
MessageBox.Show("From a1");
}
private void a2_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
MessageBox.Show("From a2");
}