If I have a backgroundWorker that has executed like this:

backgroundWorker2->RunWorkerAsync();

If I now want to cancel this, I have put this line of code at the very last line in the _DoWork event of the backgroundWorker2.
I am not sure if that works or if it is the right way to do it.

backgroundWorker2->CancelAsync();

The thing is that I use the backgroundworker for 2 things. First I will try one thing in the backgroundworker and then I will try another thing with the same backgroundworker.
So the backgroundworker needs to be "Finished" before I execute the backgroundworker again the second time.

Thank you...

CancelAsync should work as long as your worker checks the CancellationPending property on a regular basis.

I will check and try that out... thank you for help...

CancelAsync should work as long as your worker checks the CancellationPending property on a regular basis.

My beginning is this. I use the button1 to Run and Cancel the backgroundworker. I use a for loop that breaks using a Block for this.
When pressing the button the first time the backgroundworker is starting. Then to cancel, I will press the button again.

Now when I press the button again to start the backgroundworker, a message says:
"This backgroundworker is currently busy and cannot run multiple tasks concurrently"

As said I should check for the CancellationPending property.

My question should be how I would do that in this case to make it work.

int Block;
private: System::Void button1_Click(System::Object^  sender, System::EventArgs^  e) 
{
	for( int i = 0; i < 1; i++ )
	{
 
		//Start
		           if( Block == 0 )
		 {
		 	//Start the backgroundWorker2
		 	backgroundWorker2-RunWorkerAsync();
			
			 Block = 1;
			 break;	
		}

		 //Cancel	
	                 if( Block == 1 )
		 {
		 	//Cancel the backgroundWorker2
		 	backgroundWorker2->CancelAsync();

  			Block = 0;	
                             break;			 
		}
	}
}

private: System::Void backgroundWorker2_DoWork(System::Object^  sender, System::ComponentModel::DoWorkEventArgs^  e) 
{
    int count = 0;
    while(true)
    {
         count = count + 1;
    }

}

CancelAsync should work as long as your worker checks the CancellationPending property on a regular basis.

This article has been dead for over six months. Start a new discussion instead.