Problem with BackgroundWorker component?

ken76

Member
Joined
Nov 15, 2018
Messages
23
Programming Experience
5-10

When I pushed the Transfer button a second time, I get the this error message, System.InvalidOperationException: 'This BackgroundWorker is currently busy and cannot run multiple tasks concurrently.' Can someone help me with this problem?

C#:
private void buttonTransfer_Click(object sender, EventArgs e)
        {

                if (backgroundWorker1.IsBusy)
            {
                backgroundWorker1.WorkerSupportsCancellation = true;
                backgroundWorker1.CancelAsync();
                MessageBox.Show("Running!");
            }

                    richTextBoxViewStatus.Clear();
                    
            backgroundWorker1.WorkerReportsProgress = true;
            backgroundWorker1.RunWorkerAsync();

        }


private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            port.Close();
            backgroundWorker1.WorkerSupportsCancellation = true;
            backgroundWorker1.CancelAsync();
        }

      

        private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
        {
        do some work
        }
 
Calling CancelAsync doesn't actually cancel anything. It simply requests a cancellation. It's up to you to detect that request in the DoWork handler and then do whatever is appropriate to cancel the work. The RunWorkerCompleted event is then raised and it will indicate that the work was cancelled. That is where you should kick off a new task.
 
Back
Top Bottom