I get this error if I click a button that starts the backgroundworker twice.
This BackgroundWorker is currently busy and cannot run multiple tasks concurrently
How can I avoid this?
I get this error if I click a button that starts the backgroundworker twice.
This BackgroundWorker is currently busy and cannot run multiple tasks concurrently
How can I avoid this?
Simple: Don't start the BackgroundWorker twice.
You can check if it is already running by using the IsBusy property, so just change this code:
worker.RunWorkerAsync();
to this:
if( !worker.IsBusy )
worker.RunWorkerAsync();
else
MessageBox.Show("Can't run the worker twice!");
Update:
If you do actually need to launch multiple background tasks at the same time, you can simply create multiple BackgroundWorker objects
Create a new BackgroundWorker object for each operation that you want to perform. I.e., rather than:
BackgroundWorker worker = new BackgroundWorker();
worker.DoWork += new DoWorkEventHandler(worker_DoWork);
for (int i; i < max; i++) {
worker.RunWorkerAsync(i);
}
Try this:
for (int i; i < max; i++) {
BackgroundWorker worker = new BackgroundWorker();
worker.DoWork += new DoWorkEventHandler(worker_DoWork);
worker.RunWorkerAsync(i);
}
Although not the case originally asked by the OP, this can also happen due to a race condition (happened to me now, and looked for an answer) if you're using a Background worker in some sort of a producer-consumer pattern.
Example:
if (BckgrndWrkr == null)
{
BckgrndWrkr = new BackgroundWorker();
BckgrndWrkr.DoWork += DoWorkMethod;
BckgrndWrkr.RunWorkerAsync();
}
else if (!BckgrndWrkr.IsBusy)
{
BckgrndWrkr.RunWorkerAsync();
}
In this case there's a race condition: first instance instantiates a new background worker, 2nd instance reaches the else if and starts the background worker, before 1st instance reaches the RunWorkerAsync of the if block, and when it does it throws the error.
This can be avoided by adding a lock to the entire if + if else section.